Query to count of Columns??

How to count the number of columns of a table??
Thanks in Advance,
Babjan.

Ora wrote:
select count(1) from user_tab_cols where table_name = 'TEMP'
There is a slight difference between user_tab_cols and user_tab_columns. And user_tab_cols is not suitable for counting table columns:
SQL> create table tbl(n number)
  2  /
Table created.
SQL> select count(*)
  2  from all_tab_cols
  3  where owner = 'SCOTT'
  4  and table_name = 'TBL'
  5  /
  COUNT(*)
         1
SQL> select count(*)
  2  from all_tab_columns
  3  where owner = 'SCOTT'
  4  and table_name = 'TBL'
  5  /
  COUNT(*)
         1
SQL> create index tbl_fbi1
  2  on tbl(nvl(n,0))
  3  /
Index created.
SQL> select count(*)
  2  from all_tab_cols
  3  where owner = 'SCOTT'
  4  and table_name = 'TBL'
  5  /
  COUNT(*)
         2
SQL> select count(*)
  2  from all_tab_columns
  3  where owner = 'SCOTT'
  4  and table_name = 'TBL'
  5  /
  COUNT(*)
         1
SQL> SY.

Similar Messages

  • Count of columns in a query

    All,
    Could anyone please clarify me on , how we can count the column's which were used in a query.
    Ex:    SELECT ENAME, EMPNO, SAL , JOB FROM EMP; 
    --Here in the above query, I have taken 4 columns(counted manually) . Instead of counting it manually is there any other way.
    Thanks

    It sounds like you're creating dynamic SQL.  Why are you doing that?  Dynamic SQL's would seem to indicate you don't know the structure of your own database or that your application design is trying to be generic rather than being designed in proper modularized units (1 unit does 1 task, not multiple generic tasks).  99.999% of the time, people using dynamic SQL indicates that they are misusing the database or haven't designed things properly.
    If there's really a valid reason for using dynamic SQL, then of course you can do it properly and use all the features of Oracle to get information about the dynamic SQL, but that means not using something as poor as EXECUTE IMMEDIATE (which is often abused by most people), or trying to use ref cursors within PL/SQL (which are more intended for 3rd party application layers).  The power of dynamic SQL is gained from using the DBMS_SQL package... as in the following simplistic example...
    SQL> set serverout on
    SQL> create or replace procedure run_query(p_sql IN VARCHAR2) is
      2    v_v_val     varchar2(4000);
      3    v_n_val     number;
      4    v_d_val     date;
      5    v_ret       number;
      6    c           number;
      7    d           number;
      8    col_cnt     integer;
      9    f           boolean;
    10    rec_tab     dbms_sql.desc_tab;
    11    col_num     number;
    12    v_rowcount  number := 0;
    13  begin
    14    -- create a cursor
    15    c := dbms_sql.open_cursor;
    16    -- parse the SQL statement into the cursor
    17    dbms_sql.parse(c, p_sql, dbms_sql.native);
    18    -- execute the cursor
    19    d := dbms_sql.execute(c);
    20    --
    21    -- Describe the columns returned by the SQL statement
    22    dbms_sql.describe_columns(c, col_cnt, rec_tab);
    23    --
    24    -- Bind local return variables to the various columns based on their types
    25
    26    dbms_output.put_line('Number of columns in query : '||col_cnt);
    27    for j in 1..col_cnt
    28    loop
    29      case rec_tab(j).col_type
    30        when 1 then dbms_sql.define_column(c,j,v_v_val,2000); -- Varchar2
    31        when 2 then dbms_sql.define_column(c,j,v_n_val);      -- Number
    32        when 12 then dbms_sql.define_column(c,j,v_d_val);     -- Date
    33      else
    34        dbms_sql.define_column(c,j,v_v_val,2000);  -- Any other type return as varchar2
    35      end case;
    36    end loop;
    37    --
    38    -- Display what columns are being returned...
    39    dbms_output.put_line('-- Columns --');
    40    for j in 1..col_cnt
    41    loop
    42      dbms_output.put_line(rec_tab(j).col_name||' - '||case rec_tab(j).col_type when 1 then 'VARCHAR2'
    43                                                                                when 2 then 'NUMBER'
    44                                                                                when 12 then 'DATE'
    45                                                       else 'Other' end);
    46    end loop;
    47    dbms_output.put_line('-------------');
    48    --
    49    -- This part outputs the DATA
    50    loop
    51      -- Fetch a row of data through the cursor
    52      v_ret := dbms_sql.fetch_rows(c);
    53      -- Exit when no more rows
    54      exit when v_ret = 0;
    55      v_rowcount := v_rowcount + 1;
    56      dbms_output.put_line('Row: '||v_rowcount);
    57      dbms_output.put_line('--------------');
    58      -- Fetch the value of each column from the row
    59      for j in 1..col_cnt
    60      loop
    61        -- Fetch each column into the correct data type based on the description of the column
    62        case rec_tab(j).col_type
    63          when 1  then dbms_sql.column_value(c,j,v_v_val);
    64                       dbms_output.put_line(rec_tab(j).col_name||' : '||v_v_val);
    65          when 2  then dbms_sql.column_value(c,j,v_n_val);
    66                       dbms_output.put_line(rec_tab(j).col_name||' : '||v_n_val);
    67          when 12 then dbms_sql.column_value(c,j,v_d_val);
    68                       dbms_output.put_line(rec_tab(j).col_name||' : '||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'));
    69        else
    70          dbms_sql.column_value(c,j,v_v_val);
    71          dbms_output.put_line(rec_tab(j).col_name||' : '||v_v_val);
    72        end case;
    73      end loop;
    74      dbms_output.put_line('--------------');
    75    end loop;
    76    --
    77    -- Close the cursor now we have finished with it
    78    dbms_sql.close_cursor(c);
    79  END;
    80  /
    Procedure created.
    SQL> exec run_query('select empno, ename, deptno, sal from emp where deptno = 10');
    Number of columns in query : 4
    -- Columns --
    EMPNO - NUMBER
    ENAME - VARCHAR2
    DEPTNO - NUMBER
    SAL - NUMBER
    Row: 1
    EMPNO : 7782
    ENAME : CLARK
    DEPTNO : 10
    SAL : 2450
    Row: 2
    EMPNO : 7839
    ENAME : KING
    DEPTNO : 10
    SAL : 5000
    Row: 3
    EMPNO : 7934
    ENAME : MILLER
    DEPTNO : 10
    SAL : 1300
    PL/SQL procedure successfully completed.
    SQL>

  • How can i get a query to count a number of strings?

    I want the query to count for me how many holidays there are to the USA in my table. But im not sure how to get it to retreive the result of a string or varchar2 datatype. This is what i have tried so far.
    select count(COUNTRYVIS) <<this column contains all the countries visited
    from "IT220_HOLIDAYDETAILS" <<this is the table where the column is
    where COUNTRYVIS = "USA" << this is the result i want it to count
    ORA-00904: "USA": invalid identifier <<this is the error message im getting, is there a way to count strings?
    Thanks in advance!

    This has nothing to do with APEX. Please post basic SQL questions on the +{forum:id=75}+ forum.
    In any OTN forum, alll code should be posted wrapped in <tt>\...\</tt> tags as described in the FAQ:
    select count(COUNTRYVIS) -- this column contains all the countries visited
    from "IT220_HOLIDAYDETAILS" -- this is the table where the column is
    where COUNTRYVIS = "USA" -- this is the result i want it to countYou appear to be struggling with the distinction between identifiers and text literals. Hint: One uses double quotes, the other single quotes.
    Note that quoted identifiers are generally not a good idea.

  • Need query to compare the columns of 2 diff tables of 2 different schemas.

    There are two different tables(sample1, sample2) in different schemas(s_schema1, s_schema2).
    I want the query to compare the columns of two different tables of two different schemas and provide whether the data as well as the count of data in
    the column are same .
    if not provide the data which is not similar in the columns of two different table.
    NOTE:
    I need queries for both the cases.
    (i) The datatypes in columns of two different tables are same.
    (ii) The datatypes in columns of two different tables are diffrent.

    Welcome to the forum!
    Whenever you post provide your 4 digit Oracle version.
    >
    I need queries for both the cases.
    >
    Great - write the queries!
    The forum is not a coding service where you ask people to write code for you for free.
    YOU need to write the code. Then if you have a problem with the code you have written post the code you have written (using \ tags) and explain the problem you are having.
    Read the FAQ about how to ask a question on the forums.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Count(*) returns 'Column 'Count' not found' SQLException

    I am trying to get the count from a table using the following:
    String query = "SELECT COUNT(*) FROM myTable;"
    I know that the connection is open and working because I am getting back an SQLException:
    'Column 'Count' not found' .
    The same command works fine at the command line. I would be grateful for any suggestions as to why JDBC sends my app searching for a field named count in my table whereas the command line returns the expected number.
    Thanks.

    Found the problem, which is mainly my own stupidity . Is it one of Murphy's laws that the quickest way to find the solution to a problem if first embarrass yourself by asking foolish questions? Sorry to have bothered anyone.

  • Query to add a column in between existing cols of a table?

    HI All,
    I have two questions.
    1. Query to add a column in between existing cols of a table? (not at the end. This is view of an order of output fields in a report)
    2. How do I swap the contents of two columns in a table. Suppose in a table tab there are 2 cols , col1,col2 populated with some data.
    I need a query(probably) to swap the col1 and col2 values . NOT AS A RESULT SET, BUT IT NEEDS TO GET CHANGED IN THE TABLE.
    Please help !

    > 1. Query to add a column in between existing cols of
    a table? (not at the end. This is view of an order of
    output fields in a report)
    Not really sensible ito DBMS - it does not care how you want to view the data. The sequence and formats of columns are what you/the application need to specify in the SQL's projection clause.
    Also keep in mind to achieve this, the DBMS will need to rewrite the entire table to fit this new column in-between existing columns. This is not the best of ideas.
    The projection of rows is dealt with SQL statements - not with the physical storage implementation.
    > 2. How do I swap the contents of two columns in a
    table. Suppose in a table tab there are 2 cols ,
    col1,col2 populated with some data.
    I need a query(probably) to swap the col1 and col2
    values . NOT AS A RESULT SET, BUT IT NEEDS TO GET
    CHANGED IN THE TABLE.
    This seems to work:
    SQL> create table foo_tab( c1 varchar2(10), c2 varchar2(10) );
    Table created.
    SQL> insert into foo_tab select TO_CHAR(rownum), TO_CHAR(object_id) from user_objects where rownum < 11;
    10 rows created.
    SQL> commit;
    Commit complete.
    SQL> select * from foo_tab;
    C1 C2
    1 55816
    2 55817
    3 55818
    4 55721
    5 105357
    6 105358
    7 105359
    8 105360
    9 105361
    10 60222
    10 rows selected.
    SQL> update foo_tab set c1=c2, c2=c1;
    10 rows updated.
    SQL> select * from foo_tab;
    C1 C2
    55816 1
    55817 2
    55818 3
    55721 4
    105357 5
    105358 6
    105359 7
    105360 8
    105361 9
    60222 10
    10 rows selected.
    SQL>

  • SQL Query - The number of columns specified in "SQL Query" does not match t

    I am creating new UDM for tablespace alert, below is my query,however its failing with error
    SQL Query - The number of columns specified in "SQL Query" does not match the value specified in "SQL Query Output"
    I selected Metric type is number
    SQL Query Format : Two columns
    Query:
    SELECT d.tablespace_name,round(((a.bytes - NVL(f.bytes,0))*100/a.maxbytes),2)
    used_pct FROM sys.dba_tablespaces d,(select tablespace_name, sum(bytes) bytes, sum(greatest(maxbytes,bytes)) maxbytes from sys.dba_data_files group by tablespace_name) a,(select tablespace_name, sum(bytes) bytes from sys.dba_free_space group by tablespace_name) f
    WHERE d.tablespace_name = a.tablespace_name(+) AND d.tablespace_name = f.tablespace_name(+)
    AND NOT (d.extent_management = 'LOCAL' AND d.contents = 'TEMPORARY');
    Any clues why i am getting error.

    SQL> SELECT d.tablespace_name,round(((a.bytes - NVL(f.bytes,0))*100/a.maxbytes),2) used_pct
    2 FROM sys.dba_tablespaces d,(select tablespace_name, sum(bytes) bytes, sum(greatest(maxbytes,bytes)) maxbytes from sys.dba_data_files group by tablespace_name) a,(select tablespace_name, sum(bytes) bytes from sys.dba_free_space group by tablespace_name) f
    3 WHERE d.tablespace_name = a.tablespace_name(+) AND d.tablespace_name = f.tablespace_name(+)
    4 AND NOT (d.extent_management = 'LOCAL' AND d.contents = 'TEMPORARY');
    TABLESPACE_NAME USED_PCT
    MGMT_TABLESPACE .82
    SYSAUX 1.52
    UNDOTBS1 .32
    RMAN .02
    CORRUPT_TS 10.63
    USERS 0
    SYSTEM 2.26
    MGMT_ECM_DEPOT_TS .04
    MGMT_AD4J_TS 0

  • IF NEW VARIABLE IN SQL QUERY, DISPLAYS AS LAST COLUMN + rpad not working

    Hello everybody and thank you in advance,
    1) if I add a new variable to my sql query to select a column which was already in the table, it shows it in the report table as the Last column to the right. That is, if I add "street" to
    something like city, postcode, street, store, manager, etc, instead of placing street between postcode and store, it places it as i said as the last column to the right.
    2) When values are entered into the cells of the tables, yes, they do expand it to their needed lenght, But, only if it is one word. If it is two, like when i enter the value "very good"
    then it takes two lines so as with a carriage return within the cell, thus, making it too high the row. I tried to padd spaces with rpad but it did not work. something like rpad(stock, 20,' ')
    I must say that the table is in the same page where there is a Form, so as the table grows in lenth it is actually squeezing the form located right on its left.
    3) rpad did not work with the most simple syntax, but less would with what i need because it turns out i am using DECODE in order to do a conversion between value displayed and
    value returned in my select list of values, something like : DECODE (TO_CHAR (stock),'1','Deficient','2','Average','3','Good','4','Very Good',null) AS stock,
    so, i have tried to put the rpad there in several places but either it gave parsing error or it left the column empty not picking any values.
    thank you very much
    Alvaro

    Alvaro
    1) That is standard behaviour of apex builder. You can change the display order with the arrows in the report attributes column report.
    2) You will have to play with the style attributes of the column to accomplice this. For instance style="white-space:pre;" in the Element Attributes of the column attributes. White-space:normal would thread several space (' ') as 1. So no matter how many you add with rpad they will be shown as 1.
    Or set a width either as attibute or in a style class for that column.
    Nicolette

  • General Query to identify parent columns and child columns in a table

    Does anyone know a general query that can be run to identify the child records associated with the parent column within a single table.....and between other tables?
    Am I correct in assuming the parent column is the 'primary key'?
    Thanks.....I'm a new to oracle...and need some help understanding
    my company's crazy DB structure

    You can use
    User_Constraints
    User_Cons_Columns
    views to identify parent and child table columns
    SELECT * FROM User_Constraints WHERE Constraint_Type = 'R' AND Table_Name = '<TABLENAME>';
    SELECT * FROM User_Cons_columns WHERE Constraint_Name = '<Name from Above query>';
    will give you columns of the parent table (if you use value from constraint_name) and of child table (if you use value from r_constraint_name).
    HTH..

  • Writing a query to count entries for all tables

    I'd like to write a query to count the number of rows in every table for a given database. For example, if I have two tables in a database called TEST1 and TEST2 with 20 and 30 rows respectively, I'd like the output of the query to be
    TABLE_NAME          ROW_COUNT
    TEST1               20
    TEST2               30
    Any ideas?

    or justin,
    How about this
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2  t_count number;
      3  begin
      4    dbms_output.put_line('table_name          Num_rows  ');
      5    dbms_output.put_line('----------         ---------- ');
      6   for i in (select table_name  from user_tables) loop
      7    execute immediate 'select count(*) from '||i.table_name into t_count;
      8    dbms_output.put_line(i.table_name||'       '||t_count);
      9    end loop;
    10* end;
    SQL> /
    table_name          Num_rows
    EMP_TEST         0
    BOOK            2
    MONTH           36
    BOOK_SALES           65
    CURRENCY          2
    EMP          18
    BONUS          0
    DEPT          5
    SALGRADE         0
    PLAN_TABLE         0
    PL/SQL procedure successfully completed.

  • Set count of column in database......

    hi All,
    i just wanna to ask, it is possible that i can set count of column depends on data/input.
    for example;
    in common, when 2 column, code sql like:
    String query3 = "INSERT INTO Sheet5(Rule, Weight)" + "VALUES ('"+ finalRule+"', '"+weight+"')";but if n column, how?
    anybody knows or give me some idea to handle that..
    thanks.

    what do you means by using preparedStatement?
    is it like this
    String sql1 = "SELECT empno FRom emp WHERE empno = ?";
    String sql2 = "INSERT INTO emp VALUES (?,?,?,?,?,?,?,?)";
    PreparedStatement pstmt1 = conn.prepareStatement(sql1);
    PreparedStatement pstmt2 = conn.prepareStatement(sql2);
    pstmt1.setInt(1, 9999);
    ResultSet rset = pstmt1.executeQuery();
         if(rset.next()){
              System.out.println("The employee");
               rset.close();
         else {
                         pstmt2.setInt(1, 99990);
         pstmt2.setString(2, "CHARLIE");
         pstmt2.setString(3, "ANALYST");
         pstmt2.setInt(4, 7566);
         pstmt2.setString(5, "01-jan-01");
         pstmt2.setFloat(6, 12000);
         pstmt2.setFloat(7, (float)10.5);
         pstmt2.setInt(8, 10);
         pstmt2.executeUpdate();
         }so, i still need to write 8 times '?' for 8 column.
    but how if i don't know count of column?

  • Report Query using a Named Column Report Layout fails to produce PDF

    I am testing FOP and the Shared Component Report Queries query with a Named Column Report Layout. The xsl file was built using Stylus Studio and worked fine with the saved XML data file in Stylus Studio.
    500 Internal Server Error
    500 Internal Server Error
    Servlet error: An exception occurred.
    The current application deployment descriptors do not allow for including it in this response.
    Please consult the application log for details.
    I assume this is a message from FOP. What do I do now?
    tia,
    Sam

    Sam,
    I would suggest to take APEX out of the picture first and see if you can get this to work directly with your FOP solution, i.e. generate the XML data and take your XSL file and then post it directly to the FOP JSP (or whichever rendering engine you use). If this works, the problem might be somewhere in your APEX configuration. If it doesn't work, then the problem is likely in your XSL or XML structure. Here's how you can setup a static HTML page to post your XML and XSL to FOP:
    http://marcsewtz.blogspot.com/2008/06/heres-another-posting-on-pdf-printing.html
    Regards,
    Marc

  • Error querying fact: -2417217900 invalid column name

    Dear Xperts
    while validating script logic it gives error"error querying fact: -2417217900 invalid column name P_ACCT"
    P_ACCT dimension created by me.
    problem has started today while creating new script logic.
    as old logic created earlier was sucessfully validated
    new logic was created refering document 330 for bpc,so there is no scripting error
    pls guide me through this.
    thanks
    kashyap

    thanks  for ur advice
    i was able  to validate logics previously.
    i tried way you sugested but was unable to validate.
    i also  tried updating that dimension members but it was giving me some olap querry error while processing dimension after changing dimension members.
    so finally i deleted that dimension created new one did whole process again
    & was successfull
    but i wanted to know why this error could have occured
    thanks
    kashyap

  • How can I make my query to compare only columns of two tables... not the storage information?

    11GR2
    =-----------------------------------
    I am using below querry to compare two table that has same name, under two different users... But after making storage information false like below and  if the storage information is different on column level than it create "Alter modify " statements for the column ... How can I make my query to compare only columns of two tables... not the storage information?
    begin
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'PRETTY', TRUE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'SQLTERMINATOR',TRUE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'SEGMENT_ATTRIBUTES', FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'STORAGE', FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'TABLESPACE',FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'CONSTRAINTS',FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'REF_CONSTRAINTS',FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'CONSTRAINTS_AS_ALTER',FALSE);
    End;
    select REGEXP_REPLACE(dbms_metadata_diff.compare_alter('TABLE','TABLE_NAME_A','TABLE_NAME_A','USER1','USER2'),('USER1...'),'', 1, 0, 'i') from dual

    I am using below querry to compare two table that has same name, under two different users... But after making storage information false like below and  if the storage information is different on column level than it create "Alter modify " statements for the column ... How can I make my query to compare only columns of two tables... not the storage information?
    If you want help you have to SHOW us what you are doing and how you are doing it; you can't just try to tell us in your own words.
    We can't see your computer screen.

  • Count of Column

    I'm using Derby 10.5 via Command Interpreter
    I stucked at the count of column
    I need to know the command for getting number of columns used in a table .

    ibanezplayer85 wrote:
    Do you mean JTable? If so, check out the API. There's a method called [getColumnCount()|http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JTable.html#getColumnCount()] . If you're using a table model, there should also be a getColumnCount() method.
    If this isn't what you meant, you will probably have to clarify.My guess: that this isn't a Java question but rather is a Derby question, but this is just a SWAG. Who knows?

Maybe you are looking for

  • ITunes login with different apple id

    Alright, this is going to be long and complicating but I really need some help. I'm frustrated that I have to go through alot of trouble just to get apple/itunes support number. So my husband is overseas and the internet in his hotel room is really s

  • Grey screen and "incorrect number of thread records"

    I think I am in trouble. My eMac will not boot and gets stuck on the great screen with the Apple logo and the spinning windmill. I have followed the instructions in the Apple help article up to but not including "archive and install". I tried the adv

  • IPod Touch ios 5.0.1 update music backup restore issue

    i recently updated my ipod touch to ios 5.0.1 and after the update itunes restored my ipod and all of my apps but my music was not restored. I resynced to itunes and it says that all of my music is on my ipod but it isn't showing up. Thanks in advanc

  • IPhone 3G still has major probs

    got latest update monday... still lags a lot when pulling up different aspects like phone or text. even answering a phone call can put a taxation on the phone. completely stops receiving emails. it just randomly stops collecting email on ALL accounts

  • Flash locks up all browsers consistently

    Flash is locking up any browser that I use to view a video. Safari, Chrome, the browser within Newsrack all exhibit this behavior. Here is what I have done so far: OS X is up to date Uninstalled Flash following Adobe's instructions Reinstalled the la