How do I escape a table name or column name in SQL? esc_sql doesn’t do this

I can’t find a function shipped with WordPress that does this, so I created my own:

 function esc_sql_name( $name ) {
     return str_replace( "`", "``", $name );
 }

You can use it like this:

 $escaped_name = esc_sql_name( $column_name );

 $sql = $wpdb->prepare(
       "SELECT * FROM example WHERE `$escaped_name` = %s",
       $foobar
 );

Reference: