preventing select * from the query in SQL

Posted on November 5 2009 by Sachin Jain

For Team Leads, Developer don’t listen what you say :) still using * in their select queries. You can restrict them using * by using deny select on object.

This all you can do by create a dummy column in table and deny it for selection. Now user can select the rest of the columns but cannot use SELECT *.

Following is the example

CREATE TABLE tblDeny(
fieldprimary INT IDENTITY(1,1) PRIMARY KEY CLUSTERED
,fieldtest INT NULL
,fielddummy CHAR(1) NULL
);
GO

INSERT INTO tblDeny (fieldtest)
SELECT 1
UNION
SELECT 2
UNION
SELECT 3
UNION
SELECT 4
UNION
SELECT 5;
GO

DENY SELECT ON OBJECT:: tblDeny(fielddummy) TO USERLOGINID;
GO

now try this query

select * from tblDeny

or try

select count(*) from tblDeny

–Result
Msg 230, Level 14, State 1, Line 1
The SELECT permission was denied on the column ‘fielddummy’ of the object ‘tblDeny”, database ‘YOUR DATABASE’, schema ‘dbo’.

VN:F [1.8.1_1037]
Rating: 5.0/5 (1 vote cast)
VN:F [1.8.1_1037]
Rating: +1 (from 1 vote)
preventing select * from the query in SQL5.051

3 Responses to “preventing select * from the query in SQL”

  1. Rashi says:

    nice & knowledgeable article…keep writing……

    UN:F [1.8.1_1037]
    Rating: 4.0/5 (1 vote cast)
    UN:F [1.8.1_1037]
    Rating: 0 (from 0 votes)
  2. Deepak Khaitan says:

    So we see the Pro only:
    The Con is :
    The only problem will be in case you need to do some support or analysis, you need to type heavy (big) SQL each time.
    And with tools like SQL Developer its very convinient to do a select * and check the required field or take the data dump in an xls and analyse.

    UN:F [1.8.1_1037]
    Rating: 0.0/5 (0 votes cast)
    UN:F [1.8.1_1037]
    Rating: 0 (from 0 votes)
  3. Sachin Jain says:

    Hi deepak

    I don’t understand what you are saying for taking a dump data in xls file .. Here on the post I am just saying that we can prevent the using of * from the select query as it optimize our queries ?

    UA:F [1.8.1_1037]
    Rating: 0.0/5 (0 votes cast)
    UA:F [1.8.1_1037]
    Rating: 0 (from 0 votes)

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes

Powered by Sachin Jain