Databases 3 min read

Block SELECT * Queries with a One‑Line Computed Column Hack

This article explains why using SELECT * is problematic and demonstrates a simple technique—adding a computed column that triggers a divide‑by‑zero error—to block SELECT * queries while still allowing column‑specific selections.

21CTO
21CTO
21CTO
Block SELECT * Queries with a One‑Line Computed Column Hack

Everyone knows that using SELECT * is a bad practice, but it still happens. The drawbacks include returning every column (even newly added ones, which can cause issues with large types like VARCHAR(MAX)) and preventing the use of covering non‑clustered indexes because the extra data is duplicated.

To stop SELECT * without relying on code reviews, you can add a computed column that deliberately raises a divide‑by‑zero error. This forces any SELECT * statement to fail while allowing explicit column lists to work.

-- Create a simple table with a computed column that generates a divide by zero exception.
CREATE TABLE Foo (
    Col1 INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    Col2 CHAR(100) NOT NULL,
    Col3 CHAR(100) NOT NULL,
    DevelopersPain AS (1 / 0)
);
GO

-- Insert some test data
INSERT INTO Foo VALUES ('a', 'a'), ('b', 'b'), ('c', 'c');
GO

When you run SELECT * FROM Foo, the query fails with a divide‑by‑zero error:

-- A SELECT * statement doesn't work anymore, ouch...
SELECT * FROM Foo;
GO

However, selecting columns by name bypasses the computed column and works as expected:

-- This SQL statement works
SELECT Col1, Col2, Col3 FROM Foo;
GO

The method is simple but requires a schema change. Remember to apply it when designing new tables to avoid the pitfalls of SELECT *.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

performanceSQLbest practicesDatabase designselectcomputed column
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.