SQL
Database Management
Query Optimization
Data Selection
Programming

Exclude a column using SELECT * [except columnA] FROM tableA?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

When working with SQL, the SELECT * syntax is often used to retrieve all columns from a given table. However, there might be scenarios where you want to exclude one or more columns from the result set without listing all the remaining columns explicitly. Unfortunately, SQL does not directly support a syntax like SELECT * EXCEPT [columnA] FROM tableA. Instead, you need to use alternative methods to achieve this result.

Understanding the Limitations of SELECT *

Using SELECT * is simple and allows you to quickly fetch all columns from a table. Yet, this convenience comes at the cost of performance, clarity, and control over the returned data. When you know exactly which columns are needed—or which are not—specifying them can greatly enhance the performance of your queries, especially with large datasets.

Workarounds to Exclude Columns

1. Specifying All Other Columns

The most straightforward approach is to manually specify every column you want to include in your results, omitting those you do not. This method is reliable but can be cumbersome if your table has many columns.

Example: Suppose tableA has columns id, name, email, and age. To select all but the email column, you would write:

sql
SELECT id, name, age FROM tableA;

2. Using a View or a Stored Procedure

If the requirement to exclude certain columns is recurring, it might be worth the effort to create a view or a stored procedure that encapsulates the logic.

Creating a View:

sql
CREATE VIEW v_tableA AS
SELECT id, name, age FROM tableA;

Then, simply use:

sql
SELECT * FROM v_tableA;

Creating a Stored Procedure:

sql
1CREATE PROCEDURE GetTableA
2AS
3SELECT id, name, age FROM tableA;
4GO

3. Dynamic SQL

Dynamic SQL can build SQL commands dynamically and execute them. This is powerful as it can adapt to changes in the table's schema. However, caution should be used with dynamic SQL due to potential security risks like SQL injection.

Example using Dynamic SQL:

sql
1DECLARE @cols AS NVARCHAR(MAX),
2        @query  AS NVARCHAR(MAX);
3
4SELECT @cols = STUFF((SELECT ',' + QUOTENAME(column_name) 
5    FROM information_schema.columns
6    WHERE table_name = 'tableA' AND column_name != 'columnA'
7    FOR XML PATH(''), TYPE
8    ).value('.', 'NVARCHAR(MAX)'),1,1,'');
9
10SET @query = 'SELECT ' + @cols + ' FROM tableA';
11
12EXECUTE(@query);

Best Practices and Considerations

  • Code Readability: Always aim for clarity and simplicity. If the table only has a few columns, explicitly list them instead of using complex SQL scripts.
  • Performance: SELECT * can lead to unnecessarily large amounts of data being transferred and can negatively impact performance. Always select only the necessary columns.
  • Security: Be cautious with Dynamic SQL to prevent SQL injection by validating and sanitizing inputs.

Summary Table

MethodUse CaseProsCons
Listing ColumnsSmall tables or few needed columnsSimple and safeCumbersome with many columns
Using Views/Stored ProcsRecurring complex queriesClean and encapsulated codeOverhead of additional objects
Dynamic SQLFlexible column manipulation in large tablesAdapts to schema changesComplex, potential security risks

Conclusion

While SQL does not directly support excluding a column with shorthand syntax, the methods outlined provide effective alternatives. Whether you choose to manually specify columns, utilize views or stored procedures, or adopt dynamic SQL, each approach has its own advantages and limitations that can be leveraged depending on specific use cases and requirements.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.