Re: How to find first not null value in column



Martin R (martin80@xxxxxx) writes:
> How to find first not null value in column whitout chacking whole table
> (if there is a not null value then show me it and stop searching, the
> table is quite big)?

SELECT TOP 1 col FROM tbl WHERE col IS NOT NULL

Note that "first" here is not extremly well-defined, as a table by
a defintion is a unorded set of data.

If there is no index that involves col at row, SQL Server is likely
to scan the clustered index from left to right. (But in theory it
could open parallel steams, and give you a row in the middle.)

If there is an index that involves col, SQL Serer is likely to scan
that index. And if there is an index with col as the first column,
SQL Server is likely to seek that index, and you would get the lowest
value of col. If you then change "SELECT col" to "SELECT *", you may
be back on the table scan again.

If you have any additional criteria to define this "first" value, then
you need to add an ORDER BY clause to the query.


--
Erland Sommarskog, SQL Server MVP, esquel@xxxxxxxxxxxxx

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
.



Relevant Pages

  • Re: nullify delete rule?
    ... ON DELETE CASCADE will delete the child tables also. ... Books Online for SQL Server SP3 at ... > "Martin Hellat" wrote in message ...
    (microsoft.public.sqlserver.programming)
  • Re: MsSQL DBD::ODBC IsNull and undef
    ... Martin J. Evans ... On 26-Jul-2005 Brian Becker wrote: ... > ensure you tell your driver the type of the column in bind_col. ... > I'd guess this is because the SQL Server ODBC driver is looking at your ...
    (perl.dbi.users)
  • Re: Query training -- Complex queries
    ... > Update PositionsEOM ... Here you don't have a derived table, but a correlated subquery. ... UPDATE in Books Online. ... is not written for SQL Server. ...
    (microsoft.public.sqlserver.server)
  • Re: Linked Server: How to check if server exists?
    ... The root problem is described in the Books Online topic Batches. ... Rick Byham, SQL Server Books Online ... linked server don't run on those development machines not having that linked ...
    (microsoft.public.sqlserver.connect)
  • Re: STORED PROCEDURE - passing table name as a parameter
    ... T-SQL, is that you get problems if the view definition does not fit into ... will need to query other system tables, for instance syscolumns. ... Erland Sommarskog, SQL Server MVP, esquel@xxxxxxxxxxxxx ... Books Online for SQL Server 2005 at ...
    (comp.databases.ms-sqlserver)