Skip to content

Instantly share code, notes, and snippets.

@IgnoredAmbience
Created December 8, 2011 02:46
Show Gist options
  • Save IgnoredAmbience/1445889 to your computer and use it in GitHub Desktop.
Save IgnoredAmbience/1445889 to your computer and use it in GitHub Desktop.
Aren't these lovely little(!) queries? Thought not...
/* To see all columns defined */
SELECT tables.table_name, column_name, data_type, is_nullable FROM information_schema.tables JOIN information_schema.columns ON information_schema.tables.table_name=information_schema.columns.table_name ORDER BY tables.table_name, ordinal_position;
/* To list primary keys */
SELECT table_constraints.constraint_name, table_constraints.table_name, column_name FROM information_schema.table_constraints JOIN information_schema.key_column_usage ON table_constraints.constraint_name=key_column_usage.constraint_name WHERE constraint_type='PRIMARY KEY' ORDER BY table_name;
/* To list foreign keys */
SELECT foreign_key.constraint_name, foreign_key.table_name AS fk_table, fk_column_usage.column_name AS fk_column, primary_key.table_name AS pk_table, pk_column_usage.column_name AS pk_column FROM information_schema.table_constraints AS foreign_key JOIN information_schema.key_column_usage AS fk_column_usage ON foreign_key.constraint_name=fk_column_usage.constraint_name JOIN information_schema.referential_constraints ON foreign_key.constraint_name=referential_constraints.constraint_name JOIN information_schema.table_constraints AS primary_key ON referential_constraints.unique_constraint_name=primary_key.constraint_name JOIN information_schema.key_column_usage AS pk_column_usage ON primary_key.constraint_name=pk_column_usage.constraint_name AND pk_column_usage.ordinal_position=fk_column_usage.ordinal_position WHERE foreign_key.constraint_type='FOREIGN KEY' ORDER BY foreign_key.table_name;
/* List all constraints */
SELECT table_constraints.constraint_name, table_constraints.table_name, column_name, constraint_type FROM information_schema.table_constraints JOIN information_schema.key_column_usage ON table_constraints.constraint_name=key_column_usage.constraint_name ORDER BY table_name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment