Last active
December 26, 2015 11:18
-
-
Save abeger/7142341 to your computer and use it in GitHub Desktop.
Get the number of unique values in each non-empty column in each non-empty table in a MySQL database. Handy for getting a rough idea of what your data looks like. I'm sure there's a more Ruby-ic way to do this, but this gets the job done.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
c = ActiveRecord::Base.connection | |
c.execute("SHOW TABLES").each do |t| | |
table = t[0] | |
c.execute("SELECT COUNT(*) FROM `#{table}`").each do |n| | |
count = n[0] | |
next if count == 0 | |
puts | |
puts "#{table.upcase}: #{count}" | |
collist = c.execute("DESC `#{table}`").map {|x| x[0]} | |
.select { |x| !['created_at', 'updated_at', 'id', 'visible'].include?(x) } | |
count_list = c.execute("SELECT COUNT(DISTINCT " + collist.join('), COUNT(DISTINCT ') + ") FROM `#{table}`").first | |
collist.each_with_index do |col, index| | |
if count_list[index] > 0 | |
puts "#{col}: #{count_list[index]}" | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment