SHOW COLUMNS β€” Trust Nothing, Verify Everything

πŸ“– 2 minutes read




SHOW COLUMNS β€” Trust Nothing, Verify Everything

Working with an unfamiliar database or inherited codebase? Don’t guess column names β€” inspect the schema directly with SHOW COLUMNS.

I recently wasted 20 minutes debugging a query that referenced projects.title when the actual column was projects.name. One SQL command would have caught it:

SHOW COLUMNS FROM projects;

This returns the table’s structure:

+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| name        | varchar(255) | NO   |     | NULL    |                |
| status      | varchar(50)  | YES  |     | active  |                |
| created_at  | timestamp    | YES  |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

Use It Programmatically

In Laravel, you can inspect schemas at runtime:

$columns = DB::select('SHOW COLUMNS FROM ' . $table);

foreach ($columns as $col) {
    echo "{$col->Field} ({$col->Type})\n";
}

This is especially useful for:

  • Schema validation: Verify migrations match production
  • Legacy databases: Document undocumented systems
  • Dynamic queries: Build column lists programmatically
  • Debugging: Confirm column existence before querying

Alternative: Laravel’s Schema Facade

Laravel provides a cleaner API for this:

use Illuminate\Support\Facades\Schema;

// Check if column exists
if (Schema::hasColumn('projects', 'title')) {
    // Safe to use
}

// Get all columns
$columns = Schema::getColumnListing('projects');
// ['id', 'name', 'status', 'created_at', 'updated_at']

But SHOW COLUMNS gives you more metadata (type, nullable, defaults) when you need it. Way more reliable than assuming your migrations match production after years of hotfixes.


Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *