Stored Procedure For Finding Columns In MySQL

December 10, 2009 – 12:13 pm

sakila.png

Looking for instances particular column in a large schema can be a pain. Fortunately the information schema makes this pretty easy, if your columns have a consistent naming convention.

SELECT table_schema, table_name, column_name
FROM information_schema.columns
WHERE column_name LIKE '%some_name%';

Now, if we want to wrap this up into an easy to use stored procedure, we can do something like this:

drop procedure find_column;
delimiter //
CREATE PROCEDURE find_column(c varchar(255))
begin
	SET @a = CONCAT("%", c, "%");
	SELECT table_schema, table_name, column_name, column_type
		FROM information_schema.columns
		WHERE column_name LIKE @a;
end
//
delimiter ;

We need to use the concat statement in order to properly get the quotes in there without using the literal string “c” in the LIKE statement.

You can do a search as follows:

CALL find_column("some_column");

Learn more on the MySQL Stored Procedures section of mysql.com

Edit: added column type on suggested by Roland Bouman.

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  1. 3 Responses to “Stored Procedure For Finding Columns In MySQL”

  2. Ok. May I suggest adding COLUMN_TYPE?

    By Roland Bouman on Dec 10, 2009

  3. Ah, Roland! Good suggestion. I’ll update the post.

    By jon on Dec 10, 2009

  4. I use “explain extended” to find the table name that the column belongs to. I need to know the table name if no aliases are used in a join query. Thanks for sharing this procedure.

    By Shantanu Oak on Dec 23, 2009

Post a Comment