1105

We all know that to select all columns from a table, we can use

SELECT * FROM tableA

Is there a way to exclude column(s) from a table without specifying all the columns?

SELECT * [except columnA] FROM tableA

The only way that I know is to manually specify all the columns and exclude the unwanted column. This is really time consuming so I'm looking for ways to save time and effort on this, as well as future maintenance should the table has more/less columns.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 55
    It would be very convenient to have this feature, not to put in production code, but for troubleshooting purposes. Example: I have a table that has several columns I query, but I want to quickly omit a text column or two. – Micah B. Jul 10 '13 at 16:18
  • I had a need for this when working with openquery (though I neede the functionality in MySQL rather than SQL Server). I had to query an MySQL database using SQL Server. Because a MySQL table had fixed width char columns, I couldn't use a `SELECT *` query (OLE DB has issues mapping those). I couldn't specify the right columns because I had no direct access to the MySQL database, however SQL Server was kind enough to inform me of the names of the fixed width char columns... – jahu Dec 04 '14 at 09:26
  • 9
    I'd like to add another reason to do this: `SELECT DISTINCT *` except for the key column to work without duplicate rows someone else created – undrline - Reinstate Monica Aug 30 '18 at 13:50
  • 4
    I agree that it is time consuming. This is why I usually just right click on the table, choose "select top 1000 rows", then remove the columns that I don't want. – ThomasRones Jan 09 '19 at 09:02
  • 8
    not to forget: in many cases the developer does not know the columns because they can change. this is typical in data warehouses. after 6 months, they add an additional column and it should be selected without changing the code. –  Jun 13 '19 at 12:22
  • 4
    There are so many use cases for such a feature (exclude n columns from a SELECT *, as opposed to 1 column), it really ought to be added to the ANSI standard for SQL. – Dodecaphone Jun 28 '19 at 08:27
  • This is the best necropost on the server. – Pittsburgh DBA Nov 04 '19 at 20:59
  • Very good suggestion. It is tedious you have to type all columns' names simply to exclude one. – arilwan Sep 06 '22 at 22:37
  • 1
    One reason I can think of to have an all but one column is when using row_number() as row_num. Suppose I want to get the last or first record in an order table for each person. Well, it sure would be nice if I could do select * excluding row_num from ("subquery here") instead of having to copy and paste all the previous columns I wanted and removing custom logic and renamings and etc. – brian_ds Feb 15 '23 at 19:29

47 Answers47

601

You can try it this way:

/* Get the data into a temp table */
SELECT * INTO #TempTable
FROM YourTable
/* Drop the columns that are not needed */
ALTER TABLE #TempTable
DROP COLUMN ColumnToDrop
/* Get results and drop temp table */
SELECT * FROM #TempTable
DROP TABLE #TempTable
Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
Norman Skinner
  • 6,729
  • 1
  • 19
  • 22
  • 401
    Inefficient...but very creative :) – Guillermo Gutiérrez Nov 15 '11 at 20:26
  • 5
    Beautiful. I often need to include join two temp tables or a temp to another table where I don't need all the columns in the temp - especially because grouping will be involved. – VISQL Oct 09 '12 at 21:41
  • 3
    Very nice. Sure solves the problem of abstracting out the column names. – Toaster Feb 20 '13 at 12:44
  • Simply genius! I had to implement a trigger, which would throw an error instead of inserting in case of "unsuitable data". In MS SQL that means to use an "instead of insert"-trigger, and manually "INSERT INTO table SELECT * FROM inserted" at the end. However, the table had a couple of computed non-nullable columns, which were included into the inserted pseudo-table and caused trouble. I wanted to exclude these without specifying column names explicitly, because that could cause needless headscratching in the future if the table structure were to be altered. – Muuse Dec 05 '13 at 07:56
  • Shortest solution, except temp tables don't like duplicate column names. :( – Cees Timmerman Apr 18 '14 at 12:24
  • 2
    @CeesTimmerman - if you have a query involving duplicate column names, that is a separate problem, REGARDLESS of which approach you are taking. Google "SQL column rename" or "SQL column alias". Something like `SELECT table1.ID AS table1ID ...`, IIRC. – ToolmakerSteve Aug 21 '14 at 02:44
  • 3
    @ToolmakerSteve The idea of this question is to only specify columns you don't need. Naming columns would require specifying all, say, 20+ columns of a particular table. – Cees Timmerman Aug 21 '14 at 08:04
  • To say that it is "inefficient" there has to be a more efficient way to do it, answering what was asked in the post, it is the more simple and efficient way to do it. – lisandro Sep 12 '22 at 18:09
  • 1
    Love it ... combine with: `CREATE TEMPORARY TABLE TempTable LIKE OriginalTable;` and `INSERT INTO TempTable SELECT * FROM OriginalTable;` <- mysql. Temporary table exists for current connection only, i.e. it will be removed when you close the mysql session. – GuruBob Nov 10 '22 at 03:59
324

No.

Maintenance-light best practice is to specify only the required columns.

At least 2 reasons:

  • This makes your contract between client and database stable. Same data, every time
  • Performance, covering indexes

Edit (July 2011):

If you drag from Object Explorer the Columns node for a table, it puts a CSV list of columns in the Query Window for you which achieves one of your goals

demoncodemonkey
  • 11,730
  • 10
  • 61
  • 103
gbn
  • 422,506
  • 82
  • 585
  • 676
  • 9
    there are valid scenarios with SELECT *, especially in ETL routines. I think the best answer here is the one with dynamic SQL. – mishkin Feb 05 '14 at 20:16
  • 2
    There are cases where you want to select say all data for a student for statistical exploration but not bring down the wire the student id itself to bolster privacy – George Birbilis Jul 11 '14 at 16:59
  • 2
    if for nothing else, i am glad i read this post to find out about the CSV trick. that is why giving background and info around the subject is important than just straight answers. +1 from me for that. thanks – Andrei Bazanov Jun 21 '16 at 09:06
  • 1
    @all re the drag trick: cjk said this a year earlier than the edit: http://stackoverflow.com/a/2863729/2757035 – underscore_d Jun 26 '16 at 07:29
  • 145
    Although answers like this get a lot of votes, they have no value as far as I'm concerned. Conceptually, being able to "Select * Except ABC" is no more problematic that "Select *" which the language does support. The OP is clearly asking for a way to accomplish something. The person answering this question has no way of knowing if the OP wants to use this in production code or if they just have an immediate need to run a query like this while they are developing some code for the database, so the lecture about good standards contributes no value at all. – Itsme2003 Mar 13 '19 at 02:20
  • 3
    Not so easy when the column list is dynamic. – SmoveBB Mar 03 '20 at 19:55
  • 1
    I'm actually dealing with a scenario right now at work where I have my data spread across a bunch of tables, but with a shared ID. In my case, it's actually easier to just have a function on the server that takes a table name and the ID and returns values from the database. But I don't need that id, so it's just extraneous information. –  Jul 15 '21 at 17:03
  • An example of a valid need is to copy data from a test table(s) to a production version or vice versa. Assume you want an auto-key ID rather then copy the existing ID. You could use an INSERT...FROM statement with an asterisk if not for the for the ID column. One has to specify the entire list MINUS "ID" to do it right. But, you have to remember to update your query when you add a new column. By the way, SMEQL is an interesting draft query language that allows one to process the column list like any other table so that you can exclude columns via a query. – FloverOwe Aug 24 '21 at 16:16
  • 3
    Not particularly helpful when your data has 200+ columns and you need to exclude 2 and keep 198. – Patrick Conwell Nov 04 '21 at 18:29
  • +1 at this answer. Adding: One valid reason is when you're interacting with the database manually, doing some kind of analysis or investigation. That is, when you're not working with any actual application, or logic implemented in code, but rather using the database directly and SQL as a convenient way to analyze and browse it. Sometimes, you just have... data, heh. In this scenario, it could be very convenient to omit certain columns without specifying the rest, especially for complex queries. Otoh, though, in this situation it's also a lot more acceptable to create temp tables and views. – Jason C Jan 30 '22 at 01:05
  • 2
    "This makes your contract between client and database stable. Same data, every time" - In what cases does that hold for `select *` and not for `select * [except X]`? – bmk Mar 18 '22 at 14:57
  • 2
    -1. If the answer is yes, don't start your answer with "No." Just because you don't want someone to do something or don't think it's a good idea doesn't change what OP asked, and it doesn't make your answer less wrong. Answer the question, then educate. – James Aug 13 '23 at 03:52
  • 1. I am a professional. I do not need a mother to guard my SQL columns, and it is an outrageous idea to trap lists of redundant columns buried in layers of views and procedures. 2. To have your boundaries defined in SQL statements is a VERY poor practice. 3. Performance has absolutely nothing to do with it. Change in indexes alone will trigger changes in performance. 4. EXCEPT would make the code readable: A specific column was not left out by mistake. – Thomas Williams Aug 27 '23 at 20:50
103

If you don't want to write each column name manually you can use Script Table As by right clicking on table or view in SSMS like this:

enter image description here

Then you will get whole select query in New Query Editor Window then remove unwanted column like this:

enter image description here

Done

Himanshu
  • 31,810
  • 31
  • 111
  • 133
86

A modern SQL dialect like BigQuery, Databricks proposes an excellent solution.

SELECT * EXCEPT(ColumnNameX, [ColumnNameY, ...])
FROM TableA

This is a very powerful SQL syntax to avoid a long list of columns that must be constantly updated due to table column name changes. And this functionality is missing in the current SQL Server implementation, which is a pity. Hopefully, this will someday become SQL standard and make it more data scientist-friendly.

Data scientists like a quick option to shorten a query and remove some columns (due to duplication or any other reason).

https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#select-modifiers

https://docs.databricks.com/sql/language-manual/sql-ref-syntax-qry-select.html#syntax

DuckDB uses EXCLUDE instead EXCEPT https://duckdb.org/docs/sql/query_syntax/select

Velizar VESSELINOV
  • 1,806
  • 17
  • 14
86

The automated way to do this in SQL (SQL Server) is:

declare @cols varchar(max), @query varchar(max);
SELECT  @cols = STUFF
    (
        ( 
            SELECT DISTINCT '], [' + name
            FROM sys.columns
            where object_id = (
                select top 1 object_id from sys.objects
                where name = 'MyTable'
            )
            and name not in ('ColumnIDontWant1', 'ColumnIDontWant2')
            FOR XML PATH('')
        ), 1, 2, ''
    ) + ']';

SELECT @query = 'select ' + @cols + ' from MyTable';  
EXEC (@query);
Community
  • 1
  • 1
pl80
  • 966
  • 6
  • 6
  • 1
    What if you are querying from the result of a CTE or other subquery? A simple example: you might want to make a subquery that appends the result of `row_number()` to each row, then perform a join by `row_number`, then select everything *excluding the `row_number`* from the result of the join. – ely Mar 18 '16 at 05:38
55

You could create a view that has the columns you wish to select, then you can just select * from the view...

Yves M.
  • 29,855
  • 23
  • 108
  • 144
campo
  • 1,872
  • 1
  • 17
  • 19
  • 14
    At first my reaction was "how is this easier than just specifying the columns"? But then I decided that from a maintenance perspective, it might be an improvement. – ToolmakerSteve Aug 21 '14 at 02:15
  • 2
    This also supports the query optimiser rather than counteracting it with a temp table or dynamic SQL. – underscore_d Jun 26 '16 at 07:26
  • 1
    @ToolmakerSteve Also if you're doing a lot of different queries with that one column omitted, select * from the view could save you a lot of typing (and like you said, for maintenance, if you want to change that column set all around, e.g. you've added a new column, you just have to do it in the view and you can leave your queries alone). I actually go pretty heavy on views when possible in most applications, just to keep the application's SQL as short as I can. – Jason C Jan 30 '22 at 01:07
41

Yes it's possible (but not recommended).

CREATE TABLE contact (contactid int, name varchar(100), dob datetime)
INSERT INTO contact SELECT 1, 'Joe', '1974-01-01'

DECLARE @columns varchar(8000)

SELECT @columns = ISNULL(@columns + ', ','') + QUOTENAME(column_name)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'contact' AND COLUMN_NAME <> 'dob'
ORDER BY ORDINAL_POSITION

EXEC ('SELECT ' + @columns + ' FROM contact')

Explanation of the code:

  1. Declare a variable to store a comma separated list of column names. This defaults to NULL.
  2. Use a system view to determine the names of the columns in our table.
  3. Use SELECT @variable = @variable + ... FROM to concatenate the column names. This type of SELECT does not not return a result set. This is perhaps undocumented behaviour but works in every version of SQL Server. As an alternative you could use SET @variable = (SELECT ... FOR XML PATH('')) to concatenate strings.
  4. Use the ISNULL function to prepend a comma only if this is not the first column name. Use the QUOTENAME function to support spaces and punctuation in column names.
  5. Use the WHERE clause to hide columns we don't want to see.
  6. Use EXEC (@variable), also known as dynamic SQL, to resolve the column names at runtime. This is needed because we don't know the column names at compile time.
Anthony Faull
  • 17,549
  • 5
  • 55
  • 73
  • I have one question: for which reason the second select has to be put into an EXEC statement? I have seen that it is effectively necessary, but I wonder why I cannot simply write `SELECT @columns FROM contact` – Antonio Sep 09 '15 at 16:10
  • 2
    Any answer saying that something is "not recommended" should always explain WHY it’s not recommended. – bfontaine Nov 15 '22 at 11:23
21

Like the others have said there is no way to do this, but if you're using Sql Server a trick that I use is to change the output to comma separated, then do

select top 1 * from table

and cut the whole list of columns from the output window. Then you can choose which columns you want without having to type them all in.

Tom H
  • 46,766
  • 14
  • 87
  • 128
MrTelly
  • 14,657
  • 1
  • 48
  • 81
13

Basically, you cannot do what you would like - but you can get the right tools to help you out making things a bit easier.

If you look at Red-Gate's SQL Prompt, you can type "SELECT * FROM MyTable", and then move the cursor back after the "*", and hit <TAB> to expand the list of fields, and remove those few fields you don't need.

It's not a perfect solution - but a darn good one! :-) Too bad MS SQL Server Management Studio's Intellisense still isn't intelligent enough to offer this feature.......

Marc

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • This is good, but the problem is your query can become huge. It would be nice to have the "except" feature, not for prod code, but ad-hoc querying. – Micah B. Jul 10 '13 at 16:20
11
DECLARE @SQL VARCHAR(max), @TableName sysname = 'YourTableName'

SELECT @SQL = COALESCE(@SQL + ', ', '') + Name 
FROM sys.columns
WHERE OBJECT_ID = OBJECT_ID(@TableName)
AND name NOT IN ('Not This', 'Or that');

SELECT @SQL = 'SELECT ' + @SQL + ' FROM ' + @TableName

EXEC (@SQL)

UPDATE:

You can also create a stored procedure to take care of this task if you use it more often. In this example I have used the built in STRING_SPLIT() which is available on SQL Server 2016+, but if you need there are pleanty of examples of how to create it manually on SO.

CREATE PROCEDURE [usp_select_without]
@schema_name sysname = N'dbo',
@table_name sysname,
@list_of_columns_excluded nvarchar(max),
@separator nchar(1) = N','
AS
BEGIN
 DECLARE 
 @SQL nvarchar(max),
 @full_table_name nvarchar(max) = CONCAT(@schema_name, N'.', @table_name);

 SELECT @SQL = COALESCE(@SQL + ', ', '') + QUOTENAME([Name])
 FROM sys.columns sc
 LEFT JOIN STRING_SPLIT(@list_of_columns_excluded, @separator) ss ON sc.[name] = ss.[value]
 WHERE sc.OBJECT_ID = OBJECT_ID(@full_table_name, N'u')
 AND ss.[value] IS NULL;

 SELECT @SQL = N'SELECT ' + @SQL + N' FROM ' + @full_table_name;
 EXEC(@SQL)
END

And then just:

EXEC [usp_select_without] 
@table_name = N'Test_Table',
@list_of_columns_excluded = N'ID, Date, Name';
Bartosz X
  • 2,620
  • 24
  • 36
10

If you want to exclude a sensitive case column like the password for example, I do this to hide the value :

SELECT * , "" as password FROM tableName;
shA.t
  • 16,580
  • 5
  • 54
  • 111
Lu Blue
  • 335
  • 3
  • 10
  • 3
    While you should of course never store clear-text passwords in your database. At least they should be hashed with salt and maybe pepper https://security.stackexchange.com/questions/3272/password-hashing-add-salt-pepper-or-is-salt-enough#3289 – Anders_K Feb 03 '20 at 08:33
  • Getting `An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.` on this one – birgersp Jun 19 '20 at 09:11
  • 7
    Did you test this? Traditionally in SQL, this would still show the original password column and then a new column called password with a blank string. They can even have the same name. In a simple select query, your blank column won't override the original. And in a table or view creation, it will give an error for duplicate column names. – combinatorist Nov 10 '21 at 20:49
  • seems like a good idea to store empty string instead of hashed password when doing data analysis, rather than deleting the column and doing extra work. – Dendi Handian Nov 20 '22 at 04:10
9

If you are using SQL Server Management Studio then do as follows:

  1. Type in your desired tables name and select it
  2. Press Alt+F1
  3. o/p shows the columns in table.
  4. Select the desired columns
  5. Copy & paste those in your select query
  6. Fire the query.

Enjoy.

shA.t
  • 16,580
  • 5
  • 54
  • 111
asdasdasd
  • 99
  • 1
  • 1
9

no there is no way to do this. maybe you can create custom views if that's feasible in your situation

EDIT May be if your DB supports execution of dynamic sql u could write an SP and pass the columns u don't want to see to it and let it create the query dynamically and return the result to you. I think this is doable in SQL Server atleast

Ali Kazmi
  • 3,610
  • 6
  • 35
  • 51
  • 14
    It is doable but I would fire the person doing that. – Lieven Keersmaekers Apr 08 '09 at 09:29
  • Classic cleanup problem: Copy the dfata you want to keep into a temp table, truncate the big one, re-fill with the temp table. You need to exclude the identity column. – Volker Mar 09 '18 at 23:06
  • @LievenKeersmaekers What? – m4heshd Mar 16 '22 at 00:57
  • @m4heshd - a bit too strong worded. It was 13 years ago and I was even *more* foolish back then but while this answer is a good theoretical excercise, I would not want anyone on my team spending actual valuable time implementing this. Cost/benefit can't (imho) be justified. – Lieven Keersmaekers Mar 16 '22 at 08:11
8

In SQL Management Studio you can expand the columns in Object Explorer, then drag the Columns tree item into a query window to get a comma separated list of columns.

cjk
  • 45,739
  • 9
  • 81
  • 112
8

The best way to solve this is using view you can create view with required columns and retrieve data form it

example

mysql> SELECT * FROM calls;
+----+------------+---------+
| id | date       | user_id |
+----+------------+---------+
|  1 | 2016-06-22 |       1 |
|  2 | 2016-06-22 |    NULL |
|  3 | 2016-06-22 |    NULL |
|  4 | 2016-06-23 |       2 |
|  5 | 2016-06-23 |       1 |
|  6 | 2016-06-23 |       1 |
|  7 | 2016-06-23 |    NULL |
+----+------------+---------+
7 rows in set (0.06 sec)

mysql> CREATE VIEW C_VIEW AS
    ->     SELECT id,date from calls;
Query OK, 0 rows affected (0.20 sec)

mysql> select * from C_VIEW;
+----+------------+
| id | date       |
+----+------------+
|  1 | 2016-06-22 |
|  2 | 2016-06-22 |
|  3 | 2016-06-22 |
|  4 | 2016-06-23 |
|  5 | 2016-06-23 |
|  6 | 2016-06-23 |
|  7 | 2016-06-23 |
+----+------------+
7 rows in set (0.00 sec)
Mahesh Madushanka
  • 2,902
  • 2
  • 14
  • 28
  • 8
    What if the number of columns is large, say 100 & we wanted to SELECT all columns, but one. Is there a better approach? – KartikKannapur Oct 25 '16 at 16:22
  • 10
    This one kind of misses the point. You are selecting "id,date" in the second call, which, if you were going to do that, just do it in the first place. – keithpjolley May 20 '17 at 15:02
7

If we are talking of Procedures, it works with this trick to generate a new query and EXECUTE IMMEDIATE it:

SELECT LISTAGG((column_name), ', ') WITHIN GROUP (ORDER BY column_id)
INTO var_list_of_columns
FROM ALL_TAB_COLUMNS
WHERE table_name = 'PUT_HERE_YOUR_TABLE'
AND column_name NOT IN ('dont_want_this_column','neither_this_one','etc_column');
Nadeem_MK
  • 7,533
  • 7
  • 50
  • 61
AlexandreWL
  • 71
  • 1
  • 1
7

In summary you cannot do it, but I disagree with all of the comment above, there "are" scenarios where you can legitimately use a * When you create a nested query in order to select a specific range out of a whole list (such as paging) why in the world would want to specify each column on the outer select statement when you have done it in the inner?

Shrage Smilowitz
  • 24,494
  • 2
  • 28
  • 32
  • Can you use some variation of "innername.*" to represent the inner columns, similar to "SELECT table1.* ..." when doing a join? – ToolmakerSteve Aug 21 '14 at 02:17
7

Postgres sql has a way of doing it

pls refer: http://www.postgresonline.com/journal/archives/41-How-to-SELECT-ALL-EXCEPT-some-columns-in-a-table.html

The Information Schema Hack Way

SELECT 'SELECT ' || array_to_string(ARRAY(SELECT 'o' || '.' || c.column_name
        FROM information_schema.columns As c
            WHERE table_name = 'officepark' 
            AND  c.column_name NOT IN('officeparkid', 'contractor')
    ), ',') || ' FROM officepark As o' As sqlstmt

The above for my particular example table - generates an sql statement that looks like this

SELECT o.officepark,o.owner,o.squarefootage FROM officepark As o

user3393089
  • 149
  • 2
  • 10
7

Is there a way to exclude column(s) from a table without specifying all the columns?

Using declarative SQL in the usual way, no.

I think your proposed syntax is worthy and good. In fact, the relational database language 'Tutorial D' has a very similar syntax where the keywords ALL BUT are followed by a set of attributes (columns).

However, SQL's SELECT * already gets a lot a flak (@Guffa's answer here is a typical objection), so I don't think SELECT ALL BUT will get into the SQL Standard anytime soon.

I think the best 'work around' is to create a VIEW with only the columns you desire then SELECT * FROM ThatView.

onedaywhen
  • 55,269
  • 12
  • 100
  • 138
  • 1
    @underscore_d: I've now revised my answer. – onedaywhen Jun 27 '16 at 12:53
  • Cool, I agree with your last 2 paragraphs. The info about Tutorial D is interesting, although I tend to agree with those who think `select *` is questionable - very useful for ad hoc stuff and programs that need to generically handle data tables, but not so much for building (in lack of a better word) 'pure' queries. Still, not being in the ANSI standard doesn't mean Microsoft can't add it to their dialect, as with many other things, but I'm sceptical whether they would. – underscore_d Jun 27 '16 at 13:40
6

I do not know of any database that supports this (SQL Server, MySQL, Oracle, PostgreSQL). It is definitely not part of the SQL standards so I think you have to specify only the columns you want.

You could of course build your SQL statement dynamically and have the server execute it. But this opens up the possibility for SQL injection..

Ronald Wildenberg
  • 31,634
  • 14
  • 90
  • 133
6

Actually snowflake just released exclude so now you'd just:

SELECT * EXCLUDE [columnA,columnB,...] FROM tableA

Stephen Kaiser
  • 113
  • 1
  • 7
4

I know this is a little old, but I had just run into the same issue and was looking for an answer. Then I had a senior developer show me a very simple trick.

If you are using the management studio query editor, expand the database, then expand the table that you are selecting from so that you can see the columns folder.

In your select statement, just highlight the referenced columns folder above and drag and drop it into the query window. It will paste all of the columns of the table, then just simply remove the identity column from the list of columns...

imz -- Ivan Zakharyaschev
  • 4,921
  • 6
  • 53
  • 104
anonymous
  • 41
  • 1
  • 3
    Yes, but what if you have 5 joins, the idea would be to do `SELECT * Except(tableName.ColumnName) FROM ...` – Pawel Cioch Sep 30 '14 at 19:54
  • I find this useful :) I haven't known about that, nevertheless this is not an answer for topic question. – Fka Feb 10 '15 at 11:40
4

Right click table in Object Explorer, Select top 1000 rows

It'll list all columns and not *. Then remove the unwanted column(s). Should be much faster than typing it yourself.

Then when you feel this is a bit too much work, get Red Gate's SQL Prompt, and type ssf from tbl, go to the * and click tab again.

cairnz
  • 3,917
  • 1
  • 18
  • 21
3

A colleage advised a good alternative:

  • Do SELECT INTO in your preceding query (where you generate or get the data from) into a table (which you will delete when done). This will create the structure for you.
  • Do a script as CREATE to new query window.
  • Remove the unwanted columns. Format the remaining columns into a 1 liner and paste as your column list.
  • Delete the table you created.

Done...

This helped us a lot.

Charl
  • 982
  • 6
  • 12
2

That what I use often for this case:

declare @colnames varchar(max)=''

select @colnames=@colnames+','+name from syscolumns where object_id(tablename)=id and name not in (column3,column4)

SET @colnames=RIGHT(@colnames,LEN(@colnames)-1)

@colnames looks like column1,column2,column5

JustSomeGuy
  • 3,677
  • 1
  • 23
  • 31
Valeriy
  • 21
  • 1
2

I did it like this and it works just fine (version 5.5.41):

# prepare column list using info from a table of choice
SET @dyn_colums = (SELECT REPLACE(
GROUP_CONCAT(`COLUMN_NAME`), ',column_name_to_remove','') 
FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE 
`TABLE_SCHEMA`='database_name' AND `TABLE_NAME`='table_name');

# set sql command using prepared columns
SET @sql = CONCAT("SELECT ", @dyn_colums, " FROM table_name");

# prepare and execute
PREPARE statement FROM @sql;
EXECUTE statement;
Vladimir Djuricic
  • 4,323
  • 1
  • 21
  • 22
2

Sometimes the same program must handle different database stuctures. So I could not use a column list in the program to avoid errors in select statements.

* gives me all the optional fields. I check if the fields exist in the data table before use. This is my reason for using * in select.

This is how I handle excluded fields:

Dim da As New SqlDataAdapter("select * from table", cn)
da.FillSchema(dt, SchemaType.Source)
Dim fieldlist As String = ""
For Each DC As DataColumn In DT.Columns
   If DC.ColumnName.ToLower <> excludefield Then
    fieldlist = fieldlist &  DC.Columnname & ","
   End If
  Next
spenibus
  • 4,339
  • 11
  • 26
  • 35
Dusan
  • 21
  • 1
2

In Hive Sql you can do this:

set hive.support.quoted.identifiers=none;
select 
    `(unwanted_col1|unwanted_col2|unwanted_col3)?+.+`
from database.table

this gives you the rest cols

Jiadong Chen
  • 115
  • 8
  • This regex is flawed. If you want to exclude two columns `day` and `day_hour`, `(day|day_hour)?+.+` will still match `day_hour` column. That's because regex engine is eager on `|`. Although changing the order to `(day_hour|day)?+.+` can solve this issue, the better method is using negative lookahead, `(?!(day|day_hour)$).+`. – lovetl2002 Jun 28 '20 at 06:50
2

Well, it is a common best practice to specify which columns you want, instead of just specifying *. So you should just state which fields you want your select to return.

Gustavo
  • 359
  • 2
  • 5
1

I know this question is old, but I hope this can still be helpful.The answer is inspired by a discuss from SQL Server Forums. You can make this a stored procedure. It can also be modified to add more than one except fields.

DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = COALESCE(@SQL + ', ', ' ' ) + name from sys.columns where name not in ('colName1','colName2') and object_id = (Select id from sysobjects where name = 'tblName')
SELECT @SQL = 'SELECT ' + @SQL + ' FROM ' + 'tblName'
EXEC sp_executesql  @SQL
Weihui Guo
  • 3,669
  • 5
  • 34
  • 56
1

The proposed answer (stored procedure) from BartoszX didn't work for me when using a view instead of a real table.

Credit for the idea and the code below (except for my fix) belongs to BartoszX.

In order that this works for tables as well as for views, use the following code:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[select_without]
@schema_name sysname = N'dbo',
@table_name sysname,
@list_of_columns_excluded nvarchar(max),
@separator nchar(1) = N','
AS
BEGIN
 DECLARE 
 @SQL nvarchar(max),
 @full_table_name nvarchar(max) = CONCAT(@schema_name, N'.', @table_name);

 SELECT @SQL = COALESCE(@SQL + ', ', '') + QUOTENAME([Name])
 FROM sys.columns sc
 LEFT JOIN STRING_SPLIT(@list_of_columns_excluded, @separator) ss ON sc.[name] = ss.[value]
 WHERE sc.OBJECT_ID = OBJECT_ID(@full_table_name)
 AND ss.[value] IS NULL;

 SELECT @SQL = N'SELECT ' + @SQL + N' FROM ' + @full_table_name;
 EXEC(@SQL)
END
GO
John Ranger
  • 541
  • 5
  • 18
1

Try this...

=QUERY(TRANSPOSE(QUERY('Data'!A1:AH,"SELECT * ",1)),"SELECT * WHERE Col1 <> 'Column 
 name'",1)
Parzival
  • 2,051
  • 4
  • 14
  • 32
Joppe
  • 11
  • 1
1
DECLARE @Columns NVARCHAR(MAX)='',@SQL NVARCHAR(MAX)
SELECT @Columns=CASE WHEN @Columns='' THEN name ELSE @Columns+','+name END  
FROM sys.columns 
WHERE object_ID=(sELECT id FROM sysobjects WHERE name='TheTableName') and NAME!='WithoutColumnName'

SELECT @SQL='SELECT '+@Columns+' FROM dbo.TheTableName'
EXEC sp_execute @SQL
1

Of course as the other they've said you need to implement with dynamic sql. This is my implementation:

SET NOCOUNT ON

DECLARE @Table NVARCHAR(100) = 'Table' --Table to Select
DECLARE @ExcludeColumns AS TABLE (ColumnName VARCHAR(255))
INSERT INTO @ExcludeColumns VALUES ('ExcludedColumn1'),('ExcludedColumn2') --Excluded columns

DECLARE @SelectedColumns NVARCHAR(MAX) = ''
SELECT 
    @SelectedColumns += CASE WHEN LEN(@SelectedColumns) = 0 THEN '' ELSE ',' END + '[' + COLUMN_NAME + ']' 
FROM 
    INFORMATION_SCHEMA.COLUMNS 
WHERE 
    TABLE_NAME = @Table AND COLUMN_NAME NOT IN (SELECT ColumnName FROM @ExcludeColumns)

DECLARE @sqlStatement NVARCHAR(MAX) = 'SELECT ' + @SelectedColumns + ' FROM [' + @Table + ']'
PRINT @sqlStatement
EXEC (@sqlStatement)
0

In SSMS there is an easier way with IntelliSense and Aliasing. Try this

  1. Right-Click in the text editor and make sure IntelliSense is enabled.
  2. Type the query with an alias [SELECT t.* FROM tablename t].
  3. Go the text t.&ast; and delete the &ast; ,and SSMS will auto-list the columns of the f aliased table.
You can then quickly specify only the columns you want w/o having to use SSMS to write a select to another script and then do more copy/paste operations. I use this all the time.
  • Could You specify Your answer to column exclusion, please? – Kamiccolo Mar 19 '14 at 15:41
  • @Kamiccolo - what is being described by DuckWork is a MANUAL action. Cutting and pasting the desired column names. He's merely saying this is a way to more easily get at the names, without a lot of typing. It doesn't help you write a query that says "exclude this column". It just helps you create the desired list of columns, which you then paste into your query. – ToolmakerSteve Aug 21 '14 at 02:34
0

Wouldn't it be simpler to do this:

sp_help <table_name>

-Click on the 'Column_name' column> Copy> Paste (creates a vertical list) into a New Query window and just type commas in front of each column value... comment out the columns you don't want... far less typing than any code offered here and still manageable.

plo
  • 9
  • 1
  • "far less typing than any code offered here" and far more hassle than dragging the Columns node into the query editor or any of the other superior ways of getting the list. I mean what about tables with many 10s of columns? – underscore_d Jun 26 '16 at 07:34
0

The following is to generate the list of columns to use in a query (not to automate the query, as this was not specified):

SELECT 
    GROUP_CONCAT(
        CONCAT('`', `COLUMN_NAME`, '`')
        SEPARATOR ',\n'
    ) AS `cols`
FROM information_schema.`COLUMNS`
WHERE `TABLE_SCHEMA` = 'db'
AND `TABLE_NAME` = 'table_name_here'
AND `COLUMN_NAME` NOT IN ('exclude_col1', 'exclude_col2')

Will produce:

`included_col1`,
`included_col2`,
`included_col3`

You can then copy this to use in a query:

SELECT
    `included_col1`,
    `included_col2`,
    `included_col3`
FROM db.table_name_here
user678415
  • 150
  • 1
  • 4
0

If you have many columns and you want to exclude only one columns.You can use this bellow command Select * exclude(column name) from Table

  • 3
    Please take a look at the other answers that were given before. Your approach is mentioned there already. In order to keep the site clear and make it easy to find answers, we try to avoid double answers. – ahuemmer Dec 21 '22 at 09:10
  • Hi did not went through answer next time will take care of that Thank you – AtmaKumar Rai Dec 25 '22 at 03:58
0

You can get SQL Complete from devart.com, which not just expands the * wildcard just like SQL Prompt from Red Gate does (as described in cairnz's answer), but also provides a column picker drop down with checkboxes in which you can check all the columns that you want in the select list and they will be inserted automatically for you (and if you then uncheck a column it will be automatically removed from the select list).

yoel halb
  • 12,188
  • 3
  • 57
  • 52
-1

Depending on the size of your table, you can export it into Excel and transpose it to have a new table in which the columns of original table will be the rows in new table. Then take it back into your SQL database and select the rows according to the condition and insert them into another new table. Finally export this newer table to Excel and do another transpose to have your desired table and take it back to your SQL database.

Not sure if tranpose can be done within SQL database, if yes then it will be even easier.

Jeff

  • 3
    1. This isn't what is being asked. 2. This is way more work than using SQL to clone the table, and drop the desired columns. – ToolmakerSteve Aug 21 '14 at 02:37
-1

If you're using mysql-workbench, you can right click on the table explorer and click on "Send to SQL editor->Select all statement".

It sends a statement like "Select col1, col2,... from tablename".

Then remove those that you don't need.

Jagat
  • 1,392
  • 2
  • 15
  • 25
-1

This won't save time on loading from the database. But, you could always unset the column you don't want in the array it's placed in. I had several columns in a table but didn't want one particular. I was too lazy to write them all out in the SELECT statement.

$i=0;
$row_array = array();

while($row = mysqli_fetch_assoc($result)){

  $row_array[$i]=$row;
  unset($row_array[$i]['col_name']);
  $i++;
}
  • Thanks - that is a useful idea, in my situation. – ToolmakerSteve Aug 21 '14 at 02:35
  • 1
    Very poor idea, you still select more than you need which is wasteful od database resources. And it is simply a bad idea not to select specific columns in the query for production except in some edge cases. You are recommending the use of a SQL antipattern – HLGEM Apr 29 '15 at 14:49
  • an SQL antipattern but a code pattern. The alternative is pretty much to select everything but manually. –  Jul 15 '15 at 18:20
-1

If anyone here is using MySql like I was use this:

CREATE TABLE TempTable AS SELECT * FROM #YourTable; 

ALTER TABLE TempTable 
DROP COLUMN #YourColumn; 

SELECT * FROM TempTable; 
DROP TABLE TempTable;
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
Felix
  • 29
  • 1
-1

No, there isn't any way to do that, and there is no good reason to do it.

When selecting data you should never use *, you should always specify the fields that you want. The reason is that you want the query to work the same even if you later add another field to the table. Also you specify the order of the fields in the result so that rearranging fields in the table doesn't change the result.

The same would of course apply to * except if it was possible to do.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 4
    I think in most cases if you're using * you DO want to return every column (even the new ones). – Rob Jul 07 '11 at 03:07
  • @Rob: That is definitely not anything I would reccomend in production code. You would have to make the application dynamic so that it could handle the extra information for there to be any point to get it. Getting all fields could easily make the query stop working if you add fields so that they no longer fit in the database buffer. – Guffa Jul 07 '11 at 06:02
  • 2
    -1, sometimes you DO want all of the columns. In particular when dealing with CTE's and subqueries in the same query. Selecting all columns is common and usually the point; selecting all columns except *these* columns would be very useful. – jmoreno Jun 08 '12 at 17:39
  • @jmoreno: If it would be very useful, it would be available. It's very seldom useful, that's why noone implemented it. – Guffa Jun 08 '12 at 18:36
  • @Guffa: it's been implemented, although I forget where (I thought it was iAnywhere, but googling to confirm it shows otherwise). – jmoreno Jun 08 '12 at 23:09
  • @jmoreno: You're splitting hairs... and Guffa's point is still valid for subqueries. Selecting all columns is common, but using * in any context can cause unexpected behavior for the little time it saves. – Edyn Mar 06 '13 at 19:37
  • I just got done typing 20 column names in, I don't want to have to do it again, and since the inner most columns are frequently calculations, cut and paste doesn't quite do it, it's not a little time. When I go back and edit that subquery and add ANOTHER column, I AM going to want to include the additional column -- the only time I wouldn't would be when adding it to use just for a join (in which case * Except) would come in handy). – jmoreno Mar 07 '13 at 03:37
  • @jmoreno: If you put it in perspective, it's a little time. It takes you perhaps a minute to do it properly, and you will save hours of time looking for an error in your application that you would finally find was because a field from the subquery accidentally ended up in the result... – Guffa Mar 07 '13 at 08:30
  • @Guffa: I have **never** had a problem that was caused by an extra field, wrong name/missing, yes, extra, never. Of course I never access the results by index... – jmoreno Mar 07 '13 at 16:40
  • 1
    @jmoreno: It's not only the layout of the result that can cause problems. If you fetch extra fields a record may become too large to fit in the data buffer, i.e. you may start getting errors even without changing code or database layout. Also, extra data can be a problem even if you don't get an error, i.e. it will slow everything down. – Guffa Mar 07 '13 at 16:49
  • Why the downvote? If you don't explain what it is that you think is wrong, it can't improve the answer. – Guffa Jun 27 '16 at 16:55
  • Dynamic fields don't make listing them in advance too easy. – SmoveBB Mar 03 '20 at 19:56
-2

Easy solution. In SSMS, find your table, right click it and Script Table As, then Select To. The query will be written out with every column listed. Comment out or delete the column you don't want. Very fast and easy solution to ignoring a column.

  • I think right click and select 1000 rows would provide the SQL (T-SQL) that you can copy and paste and remove columns from quite quickly. Script As does not seem easier than this – Grantly Mar 04 '21 at 22:37
  • 2
    @Grantly While Select TOP 1000 does provide the columns, it also automatically runs the query. That means a shared lock, memory grant, and the associated resource contention which is overkill for what's being asked imo. – Zorkolot Jul 06 '21 at 13:51
  • If you only want the column names in a table, then in Object Explorer, click and drag the Columns Folder (the line with the folder icon) into the query window. That's a trick from one of Kendra Little's videos. https://www.youtube.com/watch?v=xz-BEDkGo9s – Zorkolot Jul 07 '21 at 14:51
-3

You can use REGEX Column Specification.

The following query selects all columns except ds and hr SELECT (ds|hr)?+.+ FROM sales

panda695
  • 25
  • 4
-8

If you're using PHP you just do your query and then you can unset an specific element:

$sql = "SELECT * FROM ........ your query";
    $result = $conection->query($sql); // execute your query
    $row_cnt = $result->num_rows;   

if ($row_cnt > 0) {
        while ($row = $result->fetch_object()) {
            unset($row->your_column_name); // Exclude column from your fetch
            $data[] = $row;
}
echo json_encode($data); // or whatever
  • Thank you for trying to be helpful. The question asks for a solution using SQL, SQL_SERVER or TSQL (see tags). Your answer may be relevant on similar questions specifying php as part of the tags, consider moving it there. – Simon Dec 01 '21 at 12:39