1

I can select the number of rows returned by a query when I select everything by doing the following:

SELECT Count(*) FROM `foo`.`bar`;

However, I now want to select how many columns are returned. Is there an easy way to do this?

4
  • 1
    There's one. The "column" that contains the count of all the rows in the table. Commented Mar 13, 2012 at 16:48
  • Do you really need this inside mysql or just inside your application? if the latter, which language is it written in? Commented Mar 13, 2012 at 16:49
  • Inside my application. I am trying to write an function that takes a MySql query as a parameter and returns a 2d array and obviously the amount of columns and rows differs each time, in C#! Commented Mar 13, 2012 at 16:50
  • 2
    SHOW COLUMNS FROM foo.bar; should do the trick. Commented Mar 13, 2012 at 16:51

3 Answers 3

3

Use the information_schema database.

SELECT 
  COUNT(COLUMN_NAME) AS numcols
FROM COLUMNS
WHERE 
  TABLE_NAME = 'bar'
  AND TABLE_SCHEMA = 'foo'

To put the two together, use:

SELECT
  (SELECT COUNT(*) FROM foo.bar) AS numrows,
  (SELECT 
      COUNT(COLUMN_NAME) AS numcols
    FROM COLUMNS
    WHERE 
      TABLE_NAME = 'bar'
      AND TABLE_SCHEMA = 'foo'
  ) AS numcols
Sign up to request clarification or add additional context in comments.

Comments

2

DESCRIBE someTable and then mysql_count_rows() on the result.

Since the question has to do with C#, I think this should work - but I haven't done C# in a long time.

MySqlConnection connection = new MySqlConnection(#...);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "DESCRIBE sometable";
connection.Open();
Reader = command.ExecuteReader();
Reader.FieldCount # this has the count of rows, and hence columns

2 Comments

The questioner is using C#, so PHP's mysql_count_rows() won't help him here. You answered before he clarified this in a comment though, I think...
Yeah @burhan answered before I clarified this! Apologies.
1

If your table mydb.mytable is MyISAM, the following should work well:

SELECT
    row_count,column_count
FROM
    (
        SELECT table_rows row_count
        FROM information_schema.tables
        WHERE table_schema = 'mydb'
        AND table_name = 'mytable'
    ) rowcount,
    (
        SELECT MAX(ordinal_position) column_count
        FROM information_schema.columns
        WHERE table_schema = 'mydb'
        AND table_name = 'mytable'
    ) columncount
;

1 Comment

Unfortunately it's InnoDB, but I didn't specify this previously.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.