Count number of distinct values for a column for all tables that contains that column

Imagine I have one Column called cdperson. With the query below I know which Tables have column cdperson
select
t.[name]fromsys.schemassinnerjoin 
sys.tables 
tons.schema_id=t.schema_idinnerjoin 
sys.columnscont.object_id=c.object_idinnerjoin 
sys.types  
donc.user_type_id=d.user_type_idwherec.name ='cdperson'
now I want to know for each table, how many distinct values of cdperson I have and I want the result ordered by the table that has more distinct values (descending)
Table1                                                                                     
   cdperson                        select distinct(cdperson) = 10
   cdadress
   quant
Table2 with 
   cdaddress                      (no column cdperson in this table)
   quant
Table3
   cdperson                        select distinct(cdperson) = 100
   value
Table 4
   cdperson                        select distinct(cdperson) = 18
   sum
I want this result ordered by number of distinct cdperson
table3   100
table4   18
table    10
Thks for your answers

I had to add schema name to the above script to make it work in AdventureWorks:
CREATE TABLE #temp(TableName sysname , CNT BIGINT)
DECLARE @QRY NVARCHAR(MAX);
SET @qry=(SELECT
N'INSERT INTO #TEMP SELECT '''+schema_name(t.schema_id)+'.'+T.[name] +''' AS TableName, COUNT (DISTINCT ProductID) DistCount FROM '+
schema_name(t.schema_id)+'.'+t.[name] +';'
FROM sys.schemas s INNER JOIN sys.tables t ON s.schema_id=t.SCHEMA_ID
INNER JOIN sys.columns c ON t.object_id=c.object_id INNER JOIN sys.types d ON c.user_type_id=d.user_type_id
WHERE c.name ='ProductID'
FOR XML PATH(''))
EXEC(@QRY)
SELECT * FROM #temp ORDER BY TableName
DROP TABLE #temp
Production.Product 504
Production.ProductCostHistory 293
Production.ProductDocument 31
Production.ProductInventory 432
Production.ProductListPriceHistory 293
Production.ProductProductPhoto 504
Production.ProductReview 3
Production.TransactionHistory 441
Production.TransactionHistoryArchive 497
Production.WorkOrder 238
Production.WorkOrderRouting 149
Purchasing.ProductVendor 211
Purchasing.PurchaseOrderDetail 211
Sales.SalesOrderDetail 266
Sales.ShoppingCartItem 3
Sales.SpecialOfferProduct 295
Kalman Toth Database & OLAP Architect
SQL Server 2014 Database Design
New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

Similar Messages

  • What kind  of  index on limited number of distinct values in a large table

    Hi all,
    can any one help me
    what kind of index on limited number of distinct values in a large table
    Thanks,

    Hi,
    it's better to do full table scan when values are evenly distributed. Indexes are good when you want to select less than 10% of all data (it depends).
    BUT you can use index when there is another data distribution - e.g. value 'Unprocessed' 1%, 'Processed' 99% (and you have computed statistics). Generally in datawarehouse you could use bitmap index, because it is small and fast, but it's not suitable in OLTP with many data modification. Then you can use b-tree index or functional index.
    create index idx on mytable (decode('Unprocessed', 1, null));This funcional index will be small and fast too, because there won't be any null values (but you must use this clause in select statement to use index).

  • How to search all columns of all tables in a database

    i need to search all columns of all tables in a database , i already write the code below , but i've got the error message below when run this script
    DECLARE
    cnt number;
    v_data VARCHAR2(20);
    BEGIN
    v_data :='5C4CA98EAC4C';
    FOR t1 IN (SELECT table_name, column_name FROM all_tab_cols where owner='admin' and DATA_TYPE='VARCHAR2') LOOP
    EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' ||t1.table_name|| ' WHERE ' ||t1.column_name || ' = :1' INTO cnt USING v_data;
    IF cnt > 0 THEN
    dbms_output.put_line( t1.table_name ||' '||t1.column_name||' '||cnt );
    END IF;
    END LOOP;
    END;
    Error report:
    ORA-00933: SQL command not properly ended
    ORA-06512: at line 7
    00933. 00000 - "SQL command not properly ended"
    *Cause:   
    *Action:
    Any help please

    SQL solutions by Michaels
    michaels>  var val varchar2(5)
    michaels>  exec :val := 'as'
    PL/SQL procedure successfully completed.
    michaels>  select distinct substr (:val, 1, 11) "Searchword",
                    substr (table_name, 1, 14) "Table",
                    substr (t.column_value.getstringval (), 1, 50) "Column/Value"
               from cols,
                    table
                       (xmlsequence
                           (dbms_xmlgen.getxmltype ('select ' || column_name
                                                    || ' from ' || table_name
                                                    || ' where upper('
                                                    || column_name
                                                    || ') like upper(''%' || :val
                                                    || '%'')'
                                                   ).extract ('ROWSET/ROW/*')
                       ) t
    --        where table_name in ('EMPLOYEES', 'JOB_HISTORY', 'DEPARTMENTS')
           order by "Table"or
    11g upwards
    SQL> select table_name,
           column_name,
           :search_string search_string,
           result
      from (select column_name,
                   table_name,
                   'ora:view("' || table_name || '")/ROW/' || column_name || '[ora:contains(text(),"%' || :search_string || '%") > 0]' str
              from cols
             where table_name in ('EMP', 'DEPT')),
           xmltable (str columns result varchar2(10) path '.')
    TABLE_NAME                     COLUMN_NAME                    SEARCH_STRING                    RESULT   
    DEPT                           DNAME                          es                               RESEARCH 
    EMP                            ENAME                          es                               JAMES    
    EMP                            JOB                            es                               SALESMAN 
    EMP                            JOB                            es                               SALESMAN 
    4 rows selected.

  • Query to get the data of all the columns in a table except any one column

    Can anyone please tell how to write a query to get the data of all the columns in a table except one particular column..
    For Example:
    Let us consider the EMP table.,
    From this table except the column comm all the remaining columns of the table should be listed
    For this we can write a query like this..
    Select empno, ename, job, mgr, sal, hiredate, deptno from emp;
    Just to avoid only one column, I mentioned all the remaining ( 7 ) columns of the table in the query..
    As the EMP table consists only 8 columns, it doesn't seem much difficult to mention all the columns in the query,
    but if a table have 100 columns in the table, then do we have to mention all the columns in the query..?
    Is there any other way of writing the query to get the required result..?
    Thanks..

    Your best best it to just list all the columns. Any other method will just cause more headaches and complicated code.
    If you really need to list all the columns for a table because you don't want to type them, just use something like...
    SQL> ed
    Wrote file afiedt.buf
      1  select trim(',' from sys_connect_by_path(column_name,',')) as columns
      2  from (select column_name, row_number() over (order by column_id) as column_id
      3        from user_tab_cols
      4        where column_name not in ('COMM')
      5        and   table_name = 'EMP'
      6       )
      7  where connect_by_isleaf = 1
      8  connect by column_id = prior column_id + 1
      9* start with column_id = 1
    SQL> /
    COLUMNS
    EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,DEPTNO
    SQL>

  • Find all tables in db with column name of a particular string?

    I'm looking for all tables in a db that have a certain column name. How can I find this?

    John,
    thanks for your answer.
    John Mcginnis wrote:
    The quick search field in the schema browser is doing client-side filtering of the list of objects. This means we can only filter on things that we already have fetched from the database, like the object name. We have no current plans to extend the types of information that can filter on, although it is possible we might add the ability to filter based on a few other types of information that we generally fetch with the object name. However, filtering by column name would require pre-fetching the lists of columns for all tables and as such is not likely to be added to the schema browsers search field.
    I'm sure you guys had a Toad review to understand how things are done there.....so
    My 2 cents are: instead of pre-fetching the columns of all tables why don't you add a button below the table drop-down list which should fetch the tables based on the filter columns condition - exactly like Toad.
    Thanks,
    Dani

  • Prepare statement to insert a row that contains Blob column. Which way is correct?

    When we make prepare statement to insert a row that contains Blob column. Which way is correct? And what is the difference? Does anyone know?
         1.  Preparestatement.setBlob(parameter number, blob type object)
         2. Preparestatement.setBlob(parameter number, inputstream type object)
    This link show the test I made.
    https://community.oracle.com/thread/3680185?sr=inbox&customTheme=otn

    When we make prepare statement to insert a row that contains Blob column. Which way is correct? And what is the difference? Does anyone know?
         1.  Preparestatement.setBlob(parameter number, blob type object)
         2. Preparestatement.setBlob(parameter number, inputstream type object)
    I answered that in your other thread and provided a link to the JDBC Dev Guide section that discusses how to work with LOBs and BFILEs.
    Did you read that doc section?
    Did you read my reply in your other thread?
    In java a BLOB is just the locator that gives you access to the actual content. In your case you got access by selecting an existing BLOB locator and getting its inputstream. That inputstream is what gives you access to the actual blob content.
    The locator is just that; it specifies the LOCATION of the blob content but it is NOT the content.

  • Optimise query on the table which contain 1000 column

    Hi ,
    I have query on the table which contain 1000 columns
    when i am executing query on same table .It is taking time .
    Select * from abc
    where col1 between start_date and end_date ;
    abc table contain 1000 columns.
    please tell me how to optimise query

    Yeah, that was my thought as well ... 1000 columns? wtf?
    I can't think of many reasons for why you'd need to do a select * on it, and the scenarios that would require that are better addressed at the DBA level, perhaps using db replication and the data pump, etc. So to start with try selecting just the data you would need.
    One thing you can do right off the bat is to partition that table by date, and also to analyze and run statistics on it (this was a nightly operation at my last job).
    You can also create a materialzed view that refreshes overnight, just on the slice of the data you need. Use a forced fast refresh to make it current before you use it.

  • Search for column in all tables

    I want to search for a column value(example instance_id=123456) in all the tables using one query rather than describing each table to find first if instance id exist and if so do a select from that table.

    You could try some sort of variation of this:
    DECLARE
       value_of_interest    NUMBER := 12345;
       vTable          ALL_TAB_COLS.TABLE_NAME%TYPE;
       vExist          ALL_TAB_COLS.COLUMN_NAME%TYPE;
    BEGIN
       DBMS_OUTPUT.PUT_LINE(RPAD('TABLE',45,' ') || ' ' || 'EXISTS');
       FOR rec in (SELECT TABLE_NAME FROM ALL_TAB_COLS WHERE COLUMN_NAME='INSTANCE_ID')
               LOOP
                       EXECUTE IMMEDIATE 'SELECT ''' || rec.table_name || ''' AS TAB,DECODE(count(*),0,''NO'',''YES'') AS EXIST FROM '
                               ||  rec.table_name
                               || ' WHERE INSTANCE_ID=:value '
                               || 'GROUP BY ''' || rec.table_name || '''' INTO vTable,vExist USING value_of_interest;
                       DBMS_OUTPUT.PUT_LINE(RPAD(vTable,45,' ') || ' ' || vExist);
               END LOOP;
    EXCEPTION
       WHEN NO_DATA_FOUND THEN
               DBMS_OUTPUT.PUT_LINE('No Results found!');
    END;Please be aware this that has not been tested, and may have to be modified for your use.

  • How to search all columns of all tables in a database for a keyword?

    Dear Team,
    i have an requirement that : i want to search all the columns of all the tables in the particular database based on the specific key word or an free text.
    example :
    table 1: columns data
    empname sam
    empid 01
    table 2 columns data
    deptname sam
    departmentid 10
    table 3 columns data
    organization name sam
    organization id 1
    when i search for text " SAM"
    it should search me from the entire database, all tables and columns of it and display the result
    output : tablename cloumn value
    table1 empname sam
    table2 deptname sam
    table3 organizationame sam
    the example is just an sample not the real data .
    please help me with sample code or any link related to it .
    thanks in advance

    Hi justin , thanx for the reply
    the basic requirement that we required is ,
    the user will just type the keyword( value in the coumn) he required and it should search all the tables and columns of the table in the database and i have to show this in the front ent in the table format. here the user will analyse the information based on the search .
    it is just like the google search we does( type the keyword in free text) it will display the result.
    so for that i have to search entire table and columns in the whole database.
    please if any one provides me the solution it will be help full for me.
    thanx in advance

  • Sum of values in same column of all tables

    On the same sheet, I have multiple tables with the same column (F) titled "AMOUNT".
    I want to get the sum of all the values in that column, from every table, without having to specify each table.
    Is there a way to do this?

    It would be nice to not have to specify each table but it can't be done that way. Nonetheless, it is easy to get those sums. Type in =SUM( then click on the column letter (F in this case) of each of those tables until you have them all then add the closing parenthesis and hit return.

  • How to make allow null for a column in all table.

    Hi,
    I have a column "col1" in all tables (user made table) , i want to make it allow null
    please tel me how can it be done using single script.
    i mean in short way.
    yours sincerely.

    yes. absolutely you can.
    Look, what i got -
    Ranit>>  select 'alter table ' || table_name || ' modify("TIMESTAMP" null) ; ' from user_tab_columns where column_name='TIMESTAMP' and nullable ='N';
    'ALTERTABLE'||TABLE_NAME||'MODIFY("TIMESTAMP"NULL);'                           
    alter table FIXED_OBJ$ modify("TIMESTAMP" null) ;                              
    alter table SUMPARTLOG$ modify("TIMESTAMP" null) ;                             
    alter table SUMDELTA$ modify("TIMESTAMP" null) ;                               
    alter table ALL_SUMDELTA modify("TIMESTAMP" null) ;                            
    alter table DBA_EXP_FILES modify("TIMESTAMP" null) ;                           
    alter table WRI$_DBU_CPU_USAGE modify("TIMESTAMP" null) ;                      
    alter table DBA_CPU_USAGE_STATISTICS modify("TIMESTAMP" null) ;                
    7 rows selected.But, it is not over.
    Either - You have to do an 'EXECUTE IMMEDIATE' over these 'alter' scripts.
    OR - Take these scripts, put it into a <script_name>.sql file and then execute this file.
    Hope you understand.
    Edited by: ranit B on Dec 22, 2012 3:17 PM
    -- code added

  • Fastest way to update column in all tables of schema

    In our schema we have two columns ColA and ColB common in all tables in our schema.
    Suppose these columns have values as below in all tables
    ColA     ColB     
    A1     B11     
    A12     B22     
    ABC     DEF     
    Now we have to update ColA and ColB where we have alphanumeric values in all tables, some tables have few hundred records and some tables have millions of records.
    Could you gurus suggest me with a fastest way to acheive this.
    What we are thinking is to write a procedure where we can input multiple tables which could be updated simultaneously and make a collection within procedure with following values
    ColA     ColA_R     ColB     ColB_R     
    A1     aa     B11     bb     
    A12     aaa     B22     bbb     
    ABC     No Update DEF     No Update     
    So whenever we have value matching A1 update it with value aa if we have value matching B11 update it with value bb and so on.
    Your inputs are welcome so that to acheive this in fastest manner.
    Thanks,
    Tony
    Edited by: tony29743 on Nov 9, 2010 9:15 AM

    I would be tempted to do it something like this:
    Create an index organized table for the cola updates (old_val, new_val) with a PK on old_val and another one for the colb Values. This could possibliy be a single table, depending on how many distinct values there were for cola and colb and if you are sure that "But if colA and colB have value A1 then it will be updated with aa".
    Then do the updates as an updateable join view something like:
    UPDATE (SELECT t1.cola, iot.new_val
            from tab1 t1, new_values_iot iot
            where t1.cola = iot.old_val)
    SET cola = new_valThis would require two rounds of updates, one for cola and one for colb, but they could be parallelized somewhat by distributing the tables to be updated through several pl/sql blocks each updating a different set of tables.
    You may be able to do it in a single query like:
    UPDATE (SELECT t1.cola, t1.colb, iota.new_val new_vala, iotb.new_val new_valb
            from tab1 t1, new_values_iot iota, new_values_iot iotb,
            where t1.cola = iota.old_val and
                  t1.cola = iotb.old_val)
    SET cola = new_vala,
        colb = new_valbHowever, given that you said there were some values in both cola and colb that did not require updating, that may not work since the join will fail on one of cola or colb if that value is not in the IOT, so you will not get all of the rows updated. If, and it is a big if, either both of cola and colb or neither of cola annd colb need to be updated in a single row, it might work. So, looking at your original examples (ABC and DEF do not require updates but A1 does), if there could be as case where cola = 'A1' and colb = 'DEF' then you will have to do it in two updates per table.
    John

  • All columns of all table in one schema

    Hi
    All,
    Oralce 10.2.0.3
    I want to count all columns in all the table in one particular schema.
    How can I do that?
    which view i should use to count all cloumns of all tables in particular schema?
    Thanks

    vishal patel wrote:
    we needed for our data conversion project..I don't know how you'll use the number of columns in all a schema for data conversion. Some columns are duplicated (e.g. PK/FK), should they really count for two ?
    A data conversion means you should actually know what are the columns used for, not how many they are.
    one more question that count include hidden columns
    what is hidden column used for ? I can not see those columns in actual table.See here an example :
    Re: Difference btwn user_tab_cols & user_tab_columns
    Nicolas.

  • Finding tables that contain a column

    Hi all,
    I am a relatively new SQL user and am trying to figure out how to find all tables that contain a particular column, eg, 'cust_id'. I have tried a bunch of different things and searched on Google but I think I don't quite have/understand the syntax I need.
    Also, how would I display a list of all the columns in all the tables?
    Thanks!

    Hi,
    apex wrote:
    Thanks for the input! I got my first question working.
    I am still trying to understand basic ideas in SQL, eg what is the all_tab_columns in Raj's link, as usually I call something from a particular table. All_tab_columns is a view in the sys schema. There are several tables and views in the sys schema whose names start with user_ or all_ (or dba_, but you may not have privileges to see those) which are collectively called the Data Dictionary . They contain information about the database itself, including the tables in the database.
    It states there that the ANALYZE command can be used to gather statistics for this view, but I have not been able to get it working.
    Eg, in Oracle SQL Developer, I type in "help <analyze>" but it doesn't tell me what the syntax of this command is, I had to use Google which gives the following
    To estimate statistics:
    ANALYZE TABLE tablename ESTIMATE STATISTICS SAMPLE 30 PERCENT;
    To compute statistics:
    ANALYZE TABLE tablename COMPUTE STATISTICS;
    But when I try the last one it just says
    table CUSTOMERS analyzed.
    but I don't see any output, and if I try to use ANALYZE all_tab_columns; it gives me an error message. When you analyze a table, a message like "table CUSTOMERS analyzed" is all you expect to see. The main purpose of anlyzing isn't to produce a report for you to read (as helpful as thant might be) but to update the data dictionary, so that Oracle knows how to do queries efficiently. For example, if you have a query like
    SELECT  *
    FROM    patients
    WHERE   birth_date  = DATE '1981-07-28'
    AND     state_abbr  = 'NY';How does the system decide whether to look for rows with the right birth_date first, or the right state? The statistics in the data dictionary might tell it that birth_date has many more ditinct values, so looking for a particular birth_date first will narrow down the search much faster than looking for a particular state.
    By the way, the ANALYZE command has been deprecated. Unless you're using a very old version of Oracle, you should be calling the dbms_stats package instead:
    http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28419/d_stats.htm#CIHBIEII
    I am using Sam's teach yourself SQL in 10 minutes which is very good at the very specific commands and functions it describes but doesn't really orient me to the language, doesn't explain how to use the help functions, or any treatment of tasks not contanied in the book. If someone can recommend another source would appreciate it. Much thanks!That's the frustrating thing about books; you can't ask them questions. (On the other hand, that's one of the nice things about this forum.)
    I can understand why the book doesn't say much about analyzing. The book is about SQL (e.g., how to create a table or write a query). Statistics are not in the scope of that book. Actually, they're not really in the scope of this forum, either. If you have questions about statistics, you're better off posting them in the "Database - General" forum:
    General Database Discussions

  • Function for search string in all table of a particular schema ? (postgres)

    Hi ,
    i want to create a function postgresql, that can able to search a string from all tables.
    I try as below.... please rectify this
    CREATE OR REPLACE FUNCTION search_string(str char(50))
    returnS character varying AS
    $BODY$
    DECLARE
         tempCount bigint ;
    record_v record;
    itemid_v bigint ;
    query varchar;
    return_v character varying := null;
    BEGIN
    for record_v in (select table_name ,column_name
                        from information_schema.columns and data_type in ('character','character varying','text')) loop
    query := 'select count(*) from '|| record_v.table_name ||' where ' || record_v.column_name || ' like ''%' || str ||'%''' ;
         execute query into tempcount;
              if (tempCount >0) then
              return      'l';
              else
              return      '2572';
              end if;
              end loop;
    END;
    $BODY$ LANGUAGE plpgsql VOLATILE
    COST 100;
    in output i need all tables in which string exists :
    like table_name      count_of_string_match

    Mr. singh wrote:
    oracle is the master of all databases - i hope u know
    if any body work on oracle .. he can right any query in any database :)Query maybe. but you were asking about functions. ANSI SQL is a pretty good standard for most normal dbs nowadays. But the procedural extensions differ more. Therefor you should go to a postgress forum to ask there. Or upgrade your database to oracle.

Maybe you are looking for

  • How do I install the RC updates to my PS CC, camera raw and Lightroom?

    How do I install the RC updates to my PS CC, camera raw and Lightroom? I have downloaded the correct versions from the Lab site but I still can't open my Nikon D-610 RAW files. The site says follow on screen instructions but I have not found any. Hel

  • Printing fails

    I have several networked printers setup on my lion server. With printer sharing setup I am able to add the printers to device groups in profile manager but when users sent print jobs they never print and the print queues report that the printer is bu

  • Access Point Specific Configurations

    Hi All, just a question of a thumb... If i had a 2 Controller Scenario with some AP Specific Configurations, for example AP Groups VLAN, and one Controller fails, the APs move to the other Controller. What about the specific config? Assume that the C

  • Can't download from Creative Cloud

    Clicking any of the download links at https://creative.adobe.com/ i get to a page with the same top black bar with the same buttons, but the white space below is all blank. http://helpx.adobe.com/creative-cloud/help/install-apps/_jcr_content/main-par

  • Pressing cntrl+left mouse click doesn't select multiple rows.

    Hi, I've got this problem after i migrated my form from 6i to 10g. In 6i version, cntrl+left mouse click used to work in order to select multiple rows on the screen. But, it's not working in 10g. Instead, Shit + left mouse click is working to select