Is select count(*) correct way to find speed

Environment I am using:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
Toad 11.6
In oracle in general, if i want to know how fast I can get data from a table (or a pipelined function), is select count(*) accurate way to do it ?
Eg:
select count(*) from table(schema_name.pkg_name.proc_name(paremter1 in 123 ))
select count(*) from table(schema_name.pkg_name.proc_name(paremter1 in 123 ))
or
select count(*) from tableA
so can i give above queries and note down the time, is this accurate way to know the fastness?

In oracle in general, if i want to know how fast I can get data from a table (or a pipelined function), is select count(*) accurate way to do it ?
There is no such thing as 'in general'.
It all depends on 'what' data you want to get if you are querying a table and exactly how the function actually works if you are calling a function.
A query that 'gets' one column very fast might take days to 'get' ALL columns.
A function that does different queries based on the parameters might return data quickly for one parameter value and be very slow for a different parameter value.
Start over and tell us what BUSINESS PROBLEM you are trying to solve.

Similar Messages

  • Select count(*) on sql statement returning zero when a matching row exists.

    Our account has an ANSI C application that checks for the existence a row on an Oracle table(s) by using the following SQL:
    int iCount = 0;
    EXEC SQL
    SELECT count(rownum) INTO :iCount
    FROM sys.all_tab_columns
    WHERE table_name IN
    (SELECT table_name FROM
    sys.all_synonyms
    WHERE upper(synonym_name) = upper(:szDestTable))
    AND upper(column_name) = upper(:szColumnName)
    AND owner = 'DBAUSER';
    The bind variables szDestTable and szColumnName are populated with values parsed from columns on another database table. This application is executed through out the day. Occasionally, the application will report a zero in the iCount when there should be a match. I have verified the szDestTable and szColumnName are populated with the correct values which would find a match and they are correct. To make matters even stranger, the application will parse the same input values and find a match (as it should). At some point during the day, and it can be at any time, the application will NOT find a match on the same file, same values. Every subsequent execution of this application will not find a match on the same values. Once the database is brought down and started up in the evening for its normal backups, the application will find a match again on the same values. This problem does not occur every day. I could be a week or a week and a half between incidents.
    I printed the contents of the sqlca.sqqlerrm.sqlerrmc field to a log file. The sqlca.sqlerrm.sqlerrmc field reported an ORA-1405 bind variable was null when the iCount was reporting a zero. When I compiled this application, I set the Proc*C flag to UNSAFE_NULLS=yes since there are other bind variable in the application that can be NULL and that is ok.
    The above SQL is compiled into the C application using the Proc*C compiler. It is compiled using the Oracle 11.2.0.2 libraries. The application is executed against an Oracle 11.2.0.2 database. The database and application are executed on an HP/Unix 11.31 platform.
    This problem did not start occurring until our account went from Oracle 10.2 to Oracle 11.2. Recently, I have changed the SQL to perform a “SELECT COUNT(rownum)” instead of the “SELECT COUNT(*)”. I compiled the application and executed the new application with the SELECT COUNT(rownum) against the same database where the same application with the SELECT COUNT(*) was failing to find a row that actually existed. The application with the SELECT COUNT(rownum) found the matching row as it should have. The new application has been executing in production for about 10 days now without any problems against ten various Oracle 11.2 databases.
    Why would SELECT COUNT(*) and SELECT COUNT(rownum) be any different?

    This forum is about C programming in general, and about using Studio C in particular.
    Your question is about Oracle database programming. You are more likely to find a helpful answer in a forum about database programming. Start here:
    https://forums.oracle.com/forums/category.jspa?categoryID=18

  • Best way to find the count of rows affected by a query

    Hi All,
    Is there a way to find the row count without actually executing the SQL statement? The count need not be accurate but it should be within acceptable limits. I know we can use 'explain plan' for this. But the value in plan_table.cardinality is way out of the actual expected count.
    We would appreciate any pointers and/or suggestions.
    Thanks
    Edited by: user779842 on May 4, 2011 2:21 AM

    maybe you can try this
    How to get estimated number of rows of query without running actual query :
    CREATE OR REPLACE FUNCTION get_rows_number (sql_select VARCHAR2, sql_id VARCHAR2) RETURN NUMBER AS
    rows_number NUMBER;
    BEGIN
    EXECUTE IMMEDIATE
    ‘EXPLAIN PLAN SET STATEMENT_ID = ‘||CHR(39) || sql_id || CHR(39)||’ FOR ‘ || sql_select;
    SELECT t.cardinality
    INTO rows_number
    FROM plan_table T
    WHERE statement_id = sql_id AND ID = 0;
    RETURN rows_number;
    END;hope it helps!

  • How to disable "Selection Security" in a correct way?

    hi experts!
    how to disable "Selection Security" in a correct way?
    !http://img689.imageshack.us/img689/2748/28668107.png!
    thanks!

    Hi...
    Open "Catalog Manager" and
    navigate to Shared -> "Shared Folder Name" (ex: Sample Sales) -> _Portal.
    Here you find all dashboards. Open the dashboard that you already enabled selection. In that dashboard folder you find one more folder with name: _selections*
    Delete the _selections* folder.
    You will get Enable option again in front end.
    All the best

  • Is there a way to Find & Replace within a selection?

    I looked in the User Guide, but I didn't find any information on how to Find & Replace just within selected text. I can see how to do it for the entire document or do it one instance at a time. Is there a trick I'm missing, or is this a missing feature?

    Hey Chuck,
    I opened Pages and used its help menu and came up with this. It does not specifically mention anything about choosing just 1 paragraph or text box, but I hope it helps you none the less.
    +Finding and Replacing Text+
    +You can find every instance of a word or phrase in your document, and optionally change it to something else.+
    +Here are ways to find and replace text:+
    +Choose Edit > Find > Find, click Simple or Advanced to set up find/replace criteria, and then click a button to conduct find/replace operations.+
    +Simple: In the Find field, type the text you want to find, and type any text you want to replace it with in the Replace field.+
    +Advanced: In addition to typing Find and Replace text, you can set up additional find/replace criteria.+
    +Replace All: Automatically conducts the find/replace operation without your review.+
    +Replace: Replaces the current selection with the replacement text.+
    +Replace & Find: Replaces the current selection with the replacement text and immediately finds the next occurrence of the Find text.+
    +Next or Previous: Finds the next or previous occurrence of the Find text.+
    +Use the other commands on the Edit > Find submenu.+
    +Find Next or Find Previous: Finds the next or previous occurrence of the current Find text.+
    +Use Selection for Find: Finds the next occurrence of the selected text.+
    +Jump to Selection: Displays the selected text when it’s not currently in view.+
    Adam

  • Speeding up select count(*)

    Hi,
    I'm using a query : - SELECT COUNT(*) FROM tebevt01 a WHERE a.DAIRY_EVENT_ID IN (SELECT dairy_event_id FROM tebevt03) AND a.CREATE_TS BETWEEN '22-JAN-04' AND '12-DEC-04'
    Is there any particular optimizer hint that I can use to speed up the retrieval of data?
    Thanks,
    Bharath

    Hi Kuljeet,
    when the auto trace is on, and when i used 'WHERE EXISTS' i got : -
    Operation     Object Name     Rows     Bytes     Cost     Object Node     In/Out     PStart     PStop
    SELECT STATEMENT Optimizer Mode=CHOOSE          1           1                     
    SORT AGGREGATE          1      22                          
    FILTER                                        
    TABLE ACCESS FULL     DRIVER1.TEBEVT01     1      22      1                     
    INDEX RANGE SCAN     DRIVER1.IEVT0301     1      13                          
    when 'ORDERED' hint was used the explain plan gave : -
    Operation     Object Name     Rows     Bytes     Cost     Object Node     In/Out     PStart     PStop
    SELECT STATEMENT Optimizer Mode=CHOOSE          1           7                     
    SORT AGGREGATE          1      35                          
    NESTED LOOPS          1      35      7                     
    VIEW     SYS.VW_NSO_1     1      13      7                     
    SORT UNIQUE          1      13      7                     
    INDEX FULL SCAN     DRIVER1.IEVT0301     1      13                          
    TABLE ACCESS BY INDEX ROWID     DRIVER1.TEBEVT01     1      22                          
    INDEX UNIQUE SCAN     DRIVER1.IEVT0101     1                               
    what do u suggest? should there not be a full table scan which I think. or should the total 'cost' be low?
    what should be the 'cost'? high or low or is this irrelevant??
    thanks buddy,
    Bharath

  • Fastest way to find parents with only one child?

    I have two very large tables (both >6 million rows) in an oracle 8i DB. They have a parent child relationship and I would like to construct a query to give me the parents that have only one child......syntactically, what's the best way to construct this query?
    I was going to try:
    select join_id
    FROM parent
    where join_id in (select join_id, count(join_id)
    FROM child
    group by join_id
    having count(*)=1)
    but then I realized that the subselect has two columns to return and the primary query is only expecting one column, so this will not work.
    I suspect there's a quick and dirty way to find out what parents have only one child....
    I thought of using rowid's but am not sure this is the best way and in the example below I tried, I'm having problems b/c of functions not being allowed in the where clause.....
    select join_id
    from child d
    where rowid in (select min(rowid)
              FROM child s
              WHERE min(d.rowid)=max(s.rowid)
              AND s.join_id=d.join_id))
    Any thoughts?

    The two tables are order_header and order_detail. The order_header carries order specific information and the detail contains item specific information.
    So if you had ordered three separate products, you would have:
    one row in the order_header table (parent)
    and three rows in the order_detail table (child)
    They are linked by order_number.
    I presented the problem this way to make it more accessible to more posters.....;)
    One possible solution that I've thought of for my problem is this:
    select join_id
    from child_table d
    where (d.rowid, d.rowid) IN (select min(rowid) MIN_ROW
                   ,max(rowid) MAX_ROW
                   FROM child_table
                   WHERE s.str_order_number=d.str_order_number
                   AND s.date>='30-JAN-2005'
                   AND s.date<='31-JAN-2005'))
    I think this might work because I think that we can safely assume that if the minimum rowid and the maximum rowid (with the same join_id ) are the same then there is only one child record.....is this logic correct?

  • "select count(*)" and "select single *" returns different result

    Good day!
    product version SAP ECC 6.0
    oracle10
    data transfers from external oracle db into customer tables using direct oracle db link
    sometimes I get case with different results from 2 statements
    *mytable has 10 rows
    *1st statement
    data: cnt type I value 0.
    select count( * ) into cnt from mytable WHERE myfield_0 = 123 and myfield_1 = '123'.
    *cnt returns 10 - correct
    *2nd statement
    select single * from  mytable WHERE myfield_0 = 123 and myfield_1 = '123'.
    *sy-dbcnt returns 0
    *sy-subrc returns 4 - incorrect, 10 rows are "invisible"
    but
    1. se16 shows correct row number
    2. I update just one row from "invisible" rows using se16 and 2nd statement returns correct result after that
    can not understand why
    thank you in advance.

    Thank you, Vishal
    but,
    general problem is that
    1. both statements have the same WHERE conditions
    2. 1st return resultset with data (sy-dbcnt=10), 2nd return empty dataset, but must return 1 in sy-dbcnt
    Yes, different meaning, you are right, but must 2nd must return 1, because of "select single *" construction, not 0.
    Dataset to process is the same, WHERE conditions are equal...
    I think the problem is that how ABAP interperets select count(*) and "select single *".
    Maybe "select count (*)" scans only PK from index page(s)? and "select single *" scans data pages? and something is wrong with that?
    I'm new in SAP and didn't find any SAP tool to trace dump of data and indexes pages with Native SQL.
    se16 shows all records.
    And why after simple manual update of just one record using se16 "select single *" returns 1?
    I've just marked one row to update, didn't change any data, then pressed "save".

  • SELECT COUNT(*)  bug

    I have a table named comments, with a column labeled book_id. In this column I have non-unique integer values (we'll say 2 rows contain the number 9)
    import flash.events.*;
    import flash.data.*
    import fl.controls.ComboBox;
    import flash.filesystem.File
    //Open database-------------------------------------------------------------
    var conn:SQLConnection = new SQLConnection();
    conn.addEventListener(SQLEvent.OPEN, openHandler);
    var dbFile:File = File.desktopDirectory.resolvePath("tarot.db");
    conn.openAsync(dbFile);
    //authorsCB.addEventListener(Event.CHANGE, loadBooks);
    function openHandler(event:SQLEvent):void
    var selectStmt:SQLStatement = new SQLStatement();
    selectStmt.sqlConnection = conn;
    // define the SQL text
    selectStmt.text = "SELECT COUNT(*) FROM comments2 WHERE book_id = 9";
    // register listeners for the result and failure (status) events
    selectStmt.addEventListener(SQLEvent.RESULT, readResultHandler);
    // execute the statement
    selectStmt.execute();
    // collect author data: author name and author ID. Populate authorCB with author name. authorID is used to match publications for the booksCB in the loadBooks() function
    function readResultHandler(event:SQLEvent):void
    var result:SQLResult = event.target.getResult();
    var numResults:int = result.data.length;
    for (var i:int = 0; i < numResults; i++)
    var row:Object = result.data[i];
    var bookID:uint = row.book_id;
    var book:String = row.book;
    var authorID:uint = row.author_id;
    //combo box named authorsCB
    authorsCB.addItem({label:bookID}); //assign table data to list box
    addChild(authorsCB);
    This code returns '0' even though my table contains two matching rows.
    If I change my select statement to "SELECT * FROM comments WHERE book_id = 9", that works.
    I'm trying to implement a query that will tell me if a particular value appears in this column. If that value appears in the table, then I want to run another query to extract the associated data.
    Ultimately I'm loading combo box 1 with author names, and combo box 2 with book titles. I then want to run a 3rd query against my comments table. My comments table contains notes about the various books, but I don't have notes about every title, so I need to test if there are comments in the table before I try to extract those comments in order to avoid throwing an error.

    Okay, I got it.
    It's very difficult to find documentation on precisely HOW Adobe AIR implements some of the more obscure functions in SQLite. Even though SELECT COUNT(*) works in the Firefox SQLite Manager, it doesn't work the same way in AIR.
    Through reviewing  the COUNT(*) function in "Learning SQL" by O'Reilly, there was an example utilized in which you point to the column you want counted BEFORE the COUNT(*) function.
    So, it becomes:
    SELECT columnName, COUNT(*)  someColumnName (optional) FROM someTable etc, etc.
    After the FROM clause you could use a WHERE, or a GROUP BY.
    Keep in mind that a GROUP clause runs after a WHERE clause.

  • Select count(*) returns double?

    I have executed a 'select count(*) from ...' statement through ODBC against Oracle9i and I am very supprised that the returned ODBC type is a 'double' and not an 'int' (or a 'numeric').
    Is this really correct?

    Did you ever get a response or figure this out?
    My problem is fairly simliar, but specific to an 11.1.0.7 and onward release of the Oracle Client.
    Current C++ Application using ODBC API calling Oracle Client 10g (all versions), 11gR1 (v11.1.0.6) returns a LONG (4-byte integer) for "SELECT COUNT(*) from tablename"
    Change Oracle client to 11gR1 (v11.1.0.7) or higher (11.2.x.y etc) and that same statement returns a DOUBLE (8-byte floating value equivalent to oracle NUMBER data type).
    Since the backend DB is the same version, there must be a client side setting (I presume) that has changed the default behaviour of this Aggregate SQL function to return a double rather than a long. I'm hoping to find such a setting that I can either set programmatically through an ODBC API call, or in the Oracle Client configuration itself.
    I even tried using SQL CAST to make it an INT SELECT CAST(COUNT(*) AS INT) FROM tablename but that still returns a DOUBLE (8-byte floating NUMBER).
    Note: given that I use ODBC, I've written alot of generic C++ code supporting the return value as LONG, as that is how it's been for 10 years via ODBC. I'd like to maintain that if possible without having to write ORACLE specific code within my applications.

  • Select Count(*) and actual row are differ: 136 rows vs 65k x 7 rows

    Dear All,
    Good morning. Need your advices. We had a view which is running and producing output to excel files. But recently after one of ours database migration, it were producing differ result: Select Count(*) and actual row are differ: 136 rows vs 65k x 7 rows. Error happen when we export out the row to csv file is produced 65000 rows x 7 worksheep. But when perform select count(*) from RTNEWWIP, result return: 136 rows.
    Is there any way to trace below sql to find where go wrong?
    The Veiw as below:
    CREATE OR REPLACE VIEW RTNEWWIP
    (FAB_ID, PO, PRD_NO, SHP_PRD_NO, LOT,
    WIP_QTY, ROUTEDESC, IN_TIME, STAY_DAY, BACK_DAY,
    WO_FCST_DATE, SHIP_FCST_DATE, SHIP_CONF_DATE, WS_DATE, ROUTERATIO,
    PROCESS, LOTSTATUS, LOTTYPE, RETICLEVERSION, PROCESSVERSION,
    ROUTESEQUENCE, PRIORITY, PROCESSGEN, PROCESSFAMILY)
    AS
    select
    --ord.order_no,
    'SILTERRA' FAB_ID,
    wip.PO_NUMBER PO,
    wip.FW_DEVICE PRD_NO,
    wip.USER_ITEM_DESCRIPTION SHP_PRD_NO,
    wip.LOT_ID LOT,
    wip.CURR_QTY WIP_QTY,
    wip.STEP_DESC ROUTEDESC,
    to_char(wip.RECORD_START_DATE,'DD-MON-YYYY HH24:MI:SS') IN_TIME,
    to_char((sysdate - wip.RECORD_START_DATE),'9999D99') STAY_DAY,
    to_char((wip.SCHEDULED_COMPLETE_DATE - sysdate),'9999D99') BACK_DAY,
    -- (sysdate - wip.RECORD_START_DATE) STAY_DAY,
    -- (wip.SCHEDULED_COMPLETE_DATE - sysdate) BACK_DAY,
    to_char(wip.SCHEDULED_COMPLETE_DATE,'DD-MON-YYYY') WO_FCST_DATE,
    to_char((wip.SCHEDULED_COMPLETE_DATE + 1),'DD-MON-YYYY') SHIP_FCST_DATE,
    --nvl(oel.attribute15, to_char(sysdate+3650,'DD-MON-YYYY')) SHIP_CONF_DATE,
    to_char(nvl(to_date(oel.attribute15,'DD-MON-YYYY'), sysdate+3650),'DD-MON-YYYY') SHIP_CONF_DATE,
    to_char(wip.LOT_START_DATE,'DD-MON-YYYY') WS_DATE,
    --wip.MASK_NO || '/' || wip.MASK_TOTAL ROUTERATIO,
    '''' ||wip.MASK_NO || '/' || wip.MASK_TOTAL ROUTERATIO,
    wip.PLAN_NAME_ACTIVE PROCESS,
    wip.LOT_STATUS LOTSTATUS,
    wip.LOT_TYPE LOTTYPE,
    0 RETICLEVERSION,
    wip.PLAN_VERSION_ACTIVE PROCESSVERSION,
    0 ROUTESEQUENCE,
    wip.PRIORITY PRIORITY,
    ' ' PROCESSGEN,
    ' ' PROCESSFAMILY
    from wip_report wip, lot_fact lf, order_fact orf, order_dim ord,
    apps.oe_order_headers_all@prod_myfabetl oeh,
    apps.oe_order_lines_all@prod_myfabetl oel
    where wip.CUSTNAME like 'Realtek%'
    --AND WIP.FW_DEVICE like '%R25C'
    and wip.ACTIVE_FACT_KEY = lf.RECORD_KEY
    and lf.ORDER_FACT_KEY = orf.RECORD_KEY
    and orf.ORDER_KEY = ord.RECORD_KEY
    and ord.ORDER_NO = to_char(oeh.order_number)
    and oeh.header_id = oel.header_id
    and orf.LINE_ITEM_NUMBER = to_char(oel.line_number)
    and orf.ITEM_SCHEDULE = to_char(oel.shipment_number)
    and wip.LOT_TYPE in ('ENX','PRA','PRD','PRT','CSK','MPW')
    union all
    select --od.order_no,'
    'SILTERRA' FAB_ID,
    od.CUST_PO PO,
    imd.FW_DEVICE_ID PRD_NO,
    nvl(orf.USER_ITEM_DESCRIPTION, nvl(imd.CUST_DEVICE_ID, imd.FW_DEVICE_ID)) SHP_PRD_NO,
    sfl.LOTID LOT,
    sfl.currentcompqty WIP_QTY,
    'CREATED' ROUTEDESC,
    to_char(to_date(substr(recordstartdate,1, 14), 'yyyymmddhh24miss'), 'DD-MON-YYYY HH24:MI:SS') IN_TIME,
    --sysdate - to_date(substr(recordstartdate,1, 14), 'yyyymmddhh24miss') STAY_DAY,
    --to_date(sfl.scheduledcompletedate,'yyyymmdd') - sysdate BACK_DAY,
    to_char(sysdate - to_date(substr(recordstartdate,1, 14), 'yyyymmddhh24miss'),'9999D99') STAY_DAY,
    to_char(to_date(sfl.scheduledcompletedate,'yyyymmdd') - sysdate,'9999D99')BACK_DAY,
    to_char(to_date(sfl.scheduledcompletedate,'yyyymmdd'),'DD-MON-YYYY') WO_FCST_DATE,
    to_char(to_date(sfl.scheduledcompletedate,'yyyymmdd') + 1, 'DD-MON-YYYY') SHIP_FCST_DATE,
    --nvl(oel.attribute15, to_char(sysdate+3650,'DD-MON-YYYY')) SHIP_CONF_DATE,
    to_char(nvl(to_date(oel.attribute15,'DD-MON-YYYY'), sysdate+3650),'DD-MON-YYYY') SHIP_CONF_DATE,
    to_char(to_date(sfl.startdate,'yyyymmdd'), 'DD-MON-YYYY') WS_DATE,
    ' ' ROUTERATIO,
    sfl.tempprocessplan PROCESS,
    sfl.currentstatus LOTSTATUS,
    sfl.currenttype LOTTYPE,
    0 RETICLEVERSION,
    0 PROCESSVERSION,
    0 ROUTESEQUENCE,
    ' ' PRIORITY,
    ' ' PROCESSGEN,
    ' ' PROCESSFAMILY
    from SIL_FW_LOTCREATED_VIEW sfl, order_dim od, order_fact orf, item_master_dim imd,
    apps.oe_order_headers_all@prod_myfabetl oeh,
    apps.oe_order_lines_all@prod_myfabetl oel
    where substr(sfl.salesorderno,1,instr(sfl.salesorderno,'-',1,1)-1)= to_char(od.ORDER_NO)
    and od.RECORD_KEY = orf.ORDER_KEY
    and od.RECORD_CURRENT_FLAG = 1
    and orf.RECORD_CURRENT_FLAG =1
    and to_char(orf.LINE_ITEM_NUMBER) = substr(sfl.salesorderno,instr(sfl.salesorderno, '-',1,1) +1, (instr(sfl.salesorderno, '.',1,1) -1) - instr(sfl.salesorderno, '-',1,1))
    and to_char(orf.ITEM_SCHEDULE) = substr(sfl.salesorderno,instr(sfl.salesorderno, '.',1,1) +1, length(salesorderno) - instr(sfl.salesorderno, '.',1,1))
    and orf.ITEM_MASTER_KEY = imd.RECORD_KEY
    and sfl.customername = 'Realtek'
    and od.ORDER_NO = to_char(oeh.order_number)
    and oeh.header_id = oel.header_id
    and orf.LINE_ITEM_NUMBER = to_char(oel.line_number)
    and orf.ITEM_SCHEDULE = to_char(oel.shipment_number);
    select count(*) from rtnewwip;
    COUNT(*)
    136
    1 row selected

    query might be referring to different environment/schema as you are using database link to access some tables.
    getting result/count from view means executing query which forms that view. try to run that query separately and see the output.
    it may help you to debug

  • Select count(*) cause time out error

    I invoke the following statement:
    select count(*) as total from table1
    where table1 is large(30000 rows), total size of the database is more than 20GB.
    The above statement will cause time out error. How to solve the problem?

    Hallo chcw,
    a timeout in a table with 30.000 records is very unusual (for a simple SELECT COUNT). From my point of view Dan is on the right way and you will have a typical blocking scenario.
    1. if you have LOBs they won't be part of a SELECT COUNT (either its a heap of a clustered index)
    2. Microosft SQL Server will ALWAYS use the smallest index for such a simple SELECT
    3. if it is a heap you will run into a blocking scenario if someone is updating records and transaction has not committed.
    4. Check the isolation level of the transactions - but I expect the standard which is "read committed".
    Just a demonstration of "SELECT COUNT" will work whether it is a clustered index or a heap. The next script will create a heap with a LOB and additional attributes:
    CREATE TABLE dbo.foo
    Id INT NOT NULL IDENTITY(1,1),
    n1 INT NOT NULL,
    n2 SMALLINT NULL,
    c1 CHAR(250) NOT NULL,
    c2 CHAR(250) NULL,
    c3 VARCHAR(MAX) NOT NULL DEFAULT (REPLICATE('A', 15000))
    GO
    Now we enter 30,000 records into the table
    SET NOCOUNT ON;
    DECLARE @i INT = 1;
    WHILE @i <= 30000
    BEGIN
    INSERT INTO dbo.foo (n1, c1) VALUES (@i, 'Just a filler');
    SET @i += 1;
    END
    GO
    Keep in mind that we have a HEAP and NO indexes! To check the IO i use the following command befor any of the following examples:
    SET STATISTICS IO ON;
    GO
    Let's start with a first try and you will check as a result the produced IO depending on the affected table partitions:
    -- USE SELECT in a HEAP
    SELECT COUNT(*) FROM dbo.foo;
    GO
    Output:
    Table 'foo'. Scan count 1, logical reads 2508, ..., lob logical reads 0,
    As you can see from the result the LOB-data won't be attached only the "in-row-data" are affected (which are stored in 2508 pages. The reason is a quite simple one: Microsoft SQL Server uses different allocation units for in-row-data and LOB
    SELECT p.object_id, p.index_id, p.rows, au.total_pages
    FROM sys.partitions AS P INNER JOIN sys.allocation_units AS AU
    ON(p.partition_id = au.container_id)
    WHERE object_id = OBJECT_ID('dbo.foo');
    Now I create a simple index on the column n1 which is an INT-datatype
    SELECT p.object_id, p.index_id, p.rows, au.total_pages
    FROM sys.partitions AS P INNER JOIN sys.allocation_units AS AU
    ON(p.partition_id = au.container_id)
    WHERE object_id = OBJECT_ID('dbo.foo');
    and run the SELECT COUNT again with the following IO-output:
    Table 'foo'. Scan count 1, logical reads 69, ...
    WOW - only 69 pages have to be read. The explanation is a quite simple one - now we have an index which is quite small. Microsoft SQL Server WILL use the smallest index of a table to scan the number of records. Let's try it again with n2 which is a smallint
    (2 bytes)
    CREATE NONCLUSTERED INDEX ix_foo_n2 ON dbo.foo (n2);
    GO
    The IO will be 62 (or less) because MORE index records a fitting to one data page!
    Conclusion is that either you have small record size or long record size - The query optimizer will always use the smallest index for the execution (that's maybe why Visahk has asked for the execution plan).
    I don't believe it is because of the "huge amount of data" but - as Dan has pointed out - it HAS TO BE a blocking scenario which can have multiple reasons. For demonstration of a blocking scenario open SSMS and start in the query windows with the following
    command(s):
    BEGIN TRANSACTION
    UPDATE dbo.foo
    SET c1 = 'This is my name'
    WHERE Id = 10000;
    -- What locks do we have now in the database
    SELECT resource_description,
    resource_associated_entity_id,
    request_mode,
    request_type
    FROM sys.dm_tran_locks AS DTL
    WHERE resource_database_id = DB_ID() AND
    resource_type != 'DATABASE';
    Your result should look like that (with differences in the entity_id and resource descriptions :)
    The above pic demonstrates the "locking chain". As you can see the slot 7 on PAGE 82400 has an exclusive lock. This means that NO OTHER request can currently obtain another lock to it!
    Now open a second query window and run a SELECT COUNT... - it will not finish!
    The reason is that the second requests has to wait for the release of the locked resources by the first transaction! Leave the statement and change back to the first transaction and finish the transaction by cancellation of the query. In the moment the locks
    have been released the second query will finish immediate.
    So - from my point of view - Dan has given the correct answer. Against wide spreaded statements a heap won't block the whole table exclusivly but - as in a cluster, too - only the row itself (see the 7 which is the slot where the record exists).
    MCM - SQL Server 2008
    MCSE - SQL Server 2012
    db Berater GmbH
    SQL Server Blog (german only)

  • How to do a 'select count' without a cursor

    I am trying to do a select which will return exactly one row, such as:
    select count(*) from orders;
    Since there is inherent overhead in using a cursor, I am trying to find a way to do this without
    generating a result set (both executeQuery and execute use result sets to return the data).
    What I am looking for is something equivalent to ESQL:
    select count(*) from orders INTO integervariable;
    Does anyone know how to do this?

    The reason for the concern is because I am issuing the
    SQL many times (thousands), with a slightly different
    'where' clause each time, and the platform I am using
    doesn't support 'prepare's.
    So, even ignoring the overhead question, is there a
    way to do this without using a result set, which
    has an inherent cursor.No - there is no way of doing this without using a resultset.

  • Correct way to get a domain's SID ?

    What is the correct way to get a domain's SID in Active Directory?
    I need to get the domain SID in order to build several of the well known SIDs (by appending the specific RID onto the domain SID).
    I've retrieved the objectSid value for the root domain object, which has a hex value of
    010400000000000515000000c5ce3fba55678398b331e1ac
    But this has a top level authority of 04, and I believe it should be 05.
    A domain admin user's tokenGroups value for the Domain Admins group is:
    010500000000000515000000c5ce3fba55678398b331e1ac00020000
    which has an 05 top level authority.
    Thanks,
    -Lance

    You may want to refer to the post titled "JNDI, Active Directory and SID's (Security Identifiers)" available at http://forum.java.sun.com/thread.jspa?threadID=585031&tstart=150 which also contains a reference on microsoft.com to the byte format of the SID.
    The value you are mistakenly referring to (bytes 1 & 2) is not the top level authority, but rather it is the count of sub-authorities.
    In this example, your domain sid has 4 sub-authorities whereas an object such as the well known group you have referred to; Domain Admins, has 5 sub-authorities.
    You may also find it easier to use the string form of the SID, rather than the byte form.

  • HT4623 Is there any way to find a lost iPhone once the phone's battery has expired?

    I have lost my iPhone(4)and the battery is dead. I have the "locate device application", however, I know the battery is dead. To my knowledge, once the battery has expired, it cannot be retrieved using the "lost device/find my device" application.?? Is this correct? If so, is there another way to find this lost iPhone?

    Thanks for taking the time to respond!!
    I didn't think so, but was hoping this was a time, that someone knew something that I didn't.

Maybe you are looking for

  • How to schedule a job from Apex?

    Hi all. I want to know the best way to schedule a job using Apex: - DBMS_JOB? - DBMS_SCHEDULER? - Build a wrapper?. - Any other thing i am not aware of?- Could an example be to much to ask? Regards, Luis ...!

  • Essbase as a source in OBIEE 11g and using lookup to Relation database

    Hello All, We are trying to implement Essbase as primary source for our obiee 11g repository and using relational database as secondary source of data. I was using a lookup functionality in repository to lookup value from one of the Essbase's Dimensi

  • Adapter?

    i have wi fi internet on second floor of home, what do i need to buy to make desktop computer on first floor work? sharing the internet, wi fi usb adapter? or wireless usb-n adapter? anything?

  • When I open a link in a new window it opens BEHIND the current window.

    links that open a new window open the window behind the current window instead of in front of it. This just started happening in the last week or so.

  • Email folders to Mac Mail?

    I'm setting up iMac Mail. What will happen to the emails that are currently contained in all my Verizon folders? Will these folders and the emails in them automatically appear in iMac Mail?