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
 

4 Responses to Stored Procedure For Finding Columns In MySQL

  1. Ok. May I suggest adding COLUMN_TYPE?

  2. jon says:

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

  3. Shantanu Oak says:

    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.

  4. 59. Thank you for some other informative website. The place else may just I get that type of info written in such a perfect means? I have a project that I am just now working on, and I have been at the look out for such info.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>