Selecting Multiple Columns Based on Condition in SQL



Selecting Multiple Columns Based On Condition

Structured Query Language is used to manage and query databases. One common use case of databases is to select single columns or multiple columns of a table based on specific conditions.

The SQL SELECT statement is used to retrieve data from a database. These conditions help filter the data to match your query. These conditions are :

  • AND and OR
  • IN
  • BETWEEN

Syntax

Following is the syntax for selecting multiple columns is ?

SELECT col 1 , col 2 ....... from table_name where condition; //If we want to select all columns from a table then there is shortcut for that SELECT * from table_name where condition; 
  • col 1 , col 2 .... ? These are the names of the columns in a table.
  • table_name ? the name of the table.
  • condition ? condition specified in the question.

Example

Below is an example, where we are going to consider the student table for getting a better understanding.

Table: Student
Roll noNameDepartmentSection
1JiyaCSEC
2TinaECEA
3RaviCSEC
4SejalMechanicalA
SELECT Roll no , Name from Student where Section ='A'; 

Output

Roll noName
2Tina
4Sejal

Using AND and OR operators

This is another criteria select multiple columns using AND and OR operators. These allow you to filter more.

Example

Select Roll No , Name from Student where Department ='CSE' AND Section='C'; 

Output

Roll noName
1Jiya
3Ravi

Using IN to match multiple values

This operator is very useful when you need to match a column's value against a list of values.

Example

Select * from Student where Department IN ('CSE', 'ECE'); 

Output

Roll noNameDepartmentSection
1JiyaCSEC
2TinaECEA
3RaviCSEC

Using BETWEEN to match multiple values

This operator is used to match the values coming in range between the values.

Example

Select Roll no, Name from Student where Roll no BETWEEN 1 and 3 ; 

Output

Roll noName
1Jiya
2Tina
3Ravi

Conclusion

We should know how to retrieve multiple columns when working with databases. It can be retrieved through many conditions like IN, BETWEEN, AND,and OR.

Updated on: 2025-03-17T16:56:58+05:30

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements
close