   (int (if *sql-string-length-fn*
          ;; If *sql-string-length-fn* is bound we can use just return AVG(LENGTH-FN(field))
          (-> korma-table
-             (select (aggregate (avg (sqlfn* *sql-string-length-fn* (keyword field-name))) :len))
+             (select (aggregate (avg (sqlfn* *sql-string-length-fn*
+                                             (raw (format "CAST(\"%s\" AS TEXT)" (name field-name)))))
+                                :len))
              first
              :len)
          ;; Otherwise we'll have to select *all* values of the Field and sum their counts in Clojure-land

   This only applies to textual fields that *do not* already have a `special_type.`"
  {:arglists '([korma-table field])}
  [korma-table {special-type :special_type, base-type :base_type, field-name :name, field-id :id, :as field}]
  (when (and (not special-type)
             (contains? #{:CharField :TextField} base-type))
    (let [percent-urls (field-percent-urls korma-table field)]
      (when (> percent-urls percent-valid-url-threshold)
        (log/info (format "Field '%s.%s' is %d%% URLs. Marking it as a URL." (:table korma-table) field-name (int (math/round (* 100 percent-urls)))))
        (upd Field field-id :special_type :url)))))

  "Mark primary-key `Fields` for TABLE as `special_type = id` if they don't already have a `special_type`."
  {:arglists '([table])}
  [{table-name :name table-id :id :keys [db pk_field]}]
  (try
    (->> (sel :many :fields [Field :name :id] :table_id table-id :special_type nil :name [in (table-pk-names @db table-name)])
         (map (fn [{field-name :name field-id :id}]
                (log/info (format "Field '%s.%s' is a primary key. Marking it as such." table-name field-name))
                (upd Field field-id :special_type :id)))
         dorun)
    (catch Throwable e
      (log/error "Caught exception in set-table-pks-if-needed!:" e))))


;; ## SET TABLE FKS
