Useful queries

Find duplicated username

User.find_by_sql('
  SELECT username, COUNT(id)
  FROM users
  GROUP BY username
  HAVING COUNT(id) > 1 ORDER BY COUNT(id)
').pluck(:username)

Find users who has no profile

User.includes(:profile).where(profile: { user_id: nil })

# OR

User.left_outer_joins(:profile).where(profile: { id: nil })

Query the latest locations of each User (user has_many :locations)

Location.where(
  id: Location.select('MAX(id) AS max_id').group(:user_id)
)