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: StudentRoll no | Name | Department | Section |
---|---|---|---|
1 | Jiya | CSE | C |
2 | Tina | ECE | A |
3 | Ravi | CSE | C |
4 | Sejal | Mechanical | A |
SELECT Roll no , Name from Student where Section ='A';
Output
Roll no | Name |
---|---|
2 | Tina |
4 | Sejal |
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 no | Name |
---|---|
1 | Jiya |
3 | Ravi |
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 no | Name | Department | Section |
---|---|---|---|
1 | Jiya | CSE | C |
2 | Tina | ECE | A |
3 | Ravi | CSE | C |
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 no | Name |
---|---|
1 | Jiya |
2 | Tina |
3 | Ravi |
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.