The Wayback Machine - https://web.archive.org/web/20240917181929/https://www.geeksforgeeks.org/selecting-multiple-columns-based-on-condition-in-sql/
Open In App

Selecting Multiple Columns Based On Condition in SQL

Last Updated : 25 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In the real-world scenario where we have to select only columns from a given table, the columns selected can be single or multiple as per requirement. For Example: Write a query that gives the names of EMPLOYEE in an organization, so here we have to pick out only the name column from that particular EMPLOYEE table. Similarly, another example of multiple columns can be: Write a query which gives the names and salaries of all employees working in an organization. So here we have to select 2 columns of name and salary.

The examples above make us understand that the selection of columns is very important while learning SQL. First, we will learn how to select a single column from a table then we will move toward multiple columns.

How to Create a Database in SQL?

First, we create our database to execute the selected queries

Step 1: Creating the database

Use the below SQL query to create a database called geeks:

CREATE DATABASE geeks;

Step 2: Using the database

USE geeks;

Step 3: Table Creation

CREATE TABLE Employee  
(
EmpID int,
FirstName varchar(255),
LastName varchar(255),
Salary INT
);

Step 4: Adding data to the table

INSERT INTO Employee VALUES(1, 'john' , 'ryther', 10000);
INSERT INTO Employee VALUES(2, 'Alex' , 'Hamilton', 20000);
INSERT INTO Employee VALUES(3, 'Sze' , 'Chauhan' , 10000);
INSERT INTO Employee VALUES(4,'Shiv', 'Chauhan', 50000);

Output:

Employee Table

Employee Table

Different Cases in SQL to Fetch Desire Output

Now, we are going to discuss different cases in SQL to fetch the desired output as per the query mentioned.

Case 1: Selecting a Single Column in SQL

In SQL, selecting any column is one of the easiest things as you have to type only the SELECT command and after that, the column name and the output will be the desired column.

Syntax:

SELECT (Column Name)

FROM (Table Name);

To make it more clear let’s take a general example of the EMPLOYEE table, which we have created above. Now, we have to select the column First_Name from the given table.

Query:

SELECT FirstName
FROM EMPLOYEE;

Output:  

output

output

Case 2: Selecting a Single Column Based on Conditions

Now, we see how we have to fetch out the first name of those employees whose salary is 10,000. From the table, it is quite clear that our desired output should be: John and Sze. To solve such queries we have to simply put a WHERE clause in our code along with the condition, as shown in the below query:

Query:

SELECT FirstName
FROM EMPLOYEE
WHERE Salary=10000;

Output:

output

output

Case 3: Selecting Multiple Columns in SQL

Selecting multiple columns in SQL with or without any condition is as simple as selecting a single column and not only simple but also the same as that. Taking our previous example further, this time we have to write a query to get a first name as well as last name from the employee table which means that we have to fetch 2 columns, the solution is very simple, we have to write all those columns names with SELECT clause which we want to fetch (In our case its first name and last name) and then table name. The syntax for which is shown below

Syntax:

SELECT column1,column2,column3…FROM table name;

In our example, the code will be as follows

Query:

SELECT FirstName,LastName
FROM Employee;

Output:

output

output

Case 4: Selecting Multiple Columns with Conditions

When we have to select multiple columns along with some condition, we put a WHERE clause and write our condition inside that clause. It is not mandatory to choose the WHERE clause there can be multiple options to put conditions depending on the query asked but most conditions are satisfied with the WHERE clause. As per the above example, this time we are going to put multiple conditions.

Example:

Write a query in SQL to select a first name and last name of an employee who has either salary of 10000 or has the last name of Chauhan.

For this query, there are three things

  • Selecting columns first name and last name i.e. SELECT First_Name, Last_Name.
  • From the employee table i.e. FROM Employee
  • Now, conditions are the tricky part as there are two conditions, let’s deal one by one
    •  Salary must be 10000 i.e. Salary=10000
    •  the Last name should be Chauhan i.e. Last_name=’chauhan’

And, hence our query has been solved, now we have to just put the above things in proper format as shown

Query:

SELECT FirstName, LastName
FROM Employee
WHERE Salary=10000 OR LastName='Chauhan';

Output:

output

output

We can match from the table that the employees which have a salary of 10000 are john and sze and the employees who have the last name Chauhan are sze and shiv which is as per our desired output.



Similar Reads

Removing Duplicate Rows (Based on Values from Multiple Columns) From SQL Table
In SQL, some rows contain duplicate entries in multiple columns(>1). For deleting such rows, we need to use the DELETE keyword along with self-joining the table with itself. The same is illustrated below. For this article, we will be using the Microsoft SQL Server as our database. Step 1: Create a Database. For this use the below command to crea
3 min read
How to Update Multiple Columns in Single Update Statement in SQL?
In this article, we will see, how to update multiple columns in a single statement in SQL. We can update multiple columns by specifying multiple columns after the SET command in the UPDATE statement. The UPDATE statement is always followed by the SET command, it specifies the column where the update is required. UPDATE for Multiple ColumnsSyntax: U
3 min read
How to Alter Multiple Columns at Once in SQL Server?
In SQL, sometimes we need to write a single query to update the values of all columns in a table. We will use the UPDATE keyword to achieve this. For this, we use a specific kind of query shown in the below demonstration. For this article, we will be using the Microsoft SQL Server as our database and Select keyword. Step 1: Create a Database. For t
3 min read
How to Find Duplicates Values Across Multiple Columns in SQL?
In SQL, sometimes we need to find duplicate entries across multiple columns in a table in a single query. We will use the GROUP BY and COUNT keywords to achieve this. For this, we use a specific kind of query shown in the below demonstration. For this article, we will be using the Microsoft SQL Server as our database and Select keyword. Step 1: Cre
2 min read
How to SELECT DISTINCT on Multiple Columns in SQL?
In the world of databases, data duplication can lead to confusion and inefficiency. SQL provides a powerful tool, SELECT DISTINCT, to retrieve unique values from columns. However, when dealing with multiple columns, the approach becomes more detailed. In this article, We will explore How to SELECT DISTINCT on multiple columns in SQL by understandin
4 min read
How to Find the Maximum of Multiple Columns in SQL
Finding the maximum value of multiple columns is one of the most common analytical tasks essential for making decisions and analyzing data. Using the MAX() function of SQL, users can find the maximum value in a single column. But to find the maximum value in multiple columns, users need to use other SQL statements like CASE or GREATEST. This articl
2 min read
How to Perform SQL Join on Multiple Columns in Same Table?
To perform SQL JOIN on multiple columns in the same table use the Self Join. Using Self Join on a table, a connection between columns of the same table can be created. We can implement Self Join on a table using “inner”, “left”, “right”, “full”, or “cartesian” join. Let us see how to perform a Self Join to connect multiple columns within the same t
3 min read
SQL Query to Convert Rows to Columns in SQL Server
In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we have a table given below: NAMECOLLEGEROLL NUMBERSUB
2 min read
Insert Multiple Values Into Multiple Tables in SQL Server
To insert multiple values into multiple tables in SQL Server, use the OUTPUT clause. The SQL OUTPUT clause allows to insert multiple values into multiple tables in a single query. Output clause clause in SQL is used to capture data affected by Data Manipulation Language (DML) statements like INSERT, UPDATE, or DELETE. SyntaxSyntax to insert multipl
2 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
SQL SERVER | IN Condition
IN condition is an alternative to multiple OR conditions in SELECT, INSERT, UPDATE, or DELETE statement. The IN operator allows multiple values to be tested against the expression and thus reduces the use of multiple OR conditions with each test value. Syntax: expression IN (value1, value2, .... value_n); Where 1. expression : value/attribute to be
1 min read
SQL Query to Return Rows Matching a Certain Condition
In SQL, sometimes we need to select matching a certain condition from the table. We will use the SELECT command along with the WHERE clause to apply a condition to achieve this in SQL. For this article. We will be using the Microsoft SQL Server as our database. Syntax: SELECT COLUMN_NAME_1, COLUMN_NAME_2, .... FROM TABLE_NAME WHERE CONDITION;Step 1
2 min read
How to Specify Condition in Count() in SQL?
In SQL, the COUNT() function is a fundamental tool for counting the number of records in a given dataset. However, in some cases, it is necessary to count the number of records based on certain conditions. Fortunately, SQL supports conditions in the COUNT() method, which allows a more complex approach to counting records. This article explores the
3 min read
SQL Query to Delete Duplicate Columns
Through this article, we will learn how to delete duplicate columns from a database table. As we know that duplicity in our database tends to be a waste of memory space. It records inaccurate data and is also unable to fetch the correct data from the database. To remove the duplicate columns we use the DISTINCT operator in the SELECT statement as f
2 min read
How to compare columns in two different tables in SQL
Here we are going to see how we can compare the columns of two different tables in SQL. We will be taking a few examples to see how we can do this in different ways. Overview :In this, we will understand overview of SQL query for required operation to perform How to compare columns in two different tables in SQL. We will understand each concept wit
4 min read
How to Compare Rows and Columns in the Same Table in SQL
In this article, we are going to see how we can compare the rows and columns of the same table in SQL. We will be taking a few examples to see how we can do this in different ways. To create the database: Syntax : CREATE database_name;CREATE Shopping To use this database: Syntax : USE database_name;USE Shopping Creating Table for making queries: Sy
2 min read
SQL Query to Find the Number of Columns in a Table
SQL stands for a structure query language, which is used in the database to retrieve data, update and modify data in relational databases like MySql, Oracle, etc. And a query is a question or request for data from the database, that is if we ask someone any question then the question is the query. Similarly when we want any data from the database t
4 min read
How to Compare Two Columns For Equality in SQL Server?
In SQL, problems require us to compare two columns for equality to achieve certain desired results. This can be achieved through the use of the =(equal to) operator between 2 columns names to be compared. For this article, we will be using the Microsoft SQL Server as our database. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN1_NAME=COLUMN2_NAME;The
2 min read
How to Select Individual Columns in SQL?
In SQL, sometimes we require to select individual columns from a table. For this, we use a specific kind of query shown in the below demonstration. For this article, we will be using the Microsoft SQL Server as our database and Select keyword. Select is the most commonly used statement in SQL. The SELECT Statement in SQL is used to retrieve or fetc
2 min read
SQL Query to Update All Columns in a Table
In SQL, sometimes we need to write a single query to update the values of all columns in a table. We will use the UPDATE keyword to achieve this. For this, we use a specific kind of query shown in the below demonstration. For this article, we will be using the Microsoft SQL Server as our database and Select keyword. Step 1: Create a Database. For t
2 min read
How to Efficiently Convert Rows to Columns in SQL?
In SQL, rows and columns are the fundamental building blocks of a database. Rows represent individual records, while columns represent the attributes or characteristics of those records. However, there may be instances where we need to convert rows to columns in order to better analyze and manipulate data. This process is known as "pivoting" and ca
5 min read
How to Get the Type of Columns in SQL
In SQL, the types of columns in a database table play a fundamental role in data management and query execution. Each column is designed to store specific types of data, such as numbers, text, dates, or binary data. Understanding these column types is essential for effective database design, query optimization, and ensuring data integrity. In this
4 min read
How to Create Unique Constraint with NULL Columns in SQL
In SQL databases, maintaining data integrity is crucial, and one common requirement is applying uniqueness among certain columns. However, handling NULL values in these columns can be challenging. By creating a unique constraint with NULL columns, we can ensure that non-NULL values are unique while allowing multiple rows with NULL values. In this a
5 min read
SQL Query to Update Columns Values With Column of Another Table
To update column values with the column values of another table, use the nested statement feature of SQL. Using the feature, we can select data from two tables, and update data in one table based on data from another table. Using JOIN also allows to connection of two tables, and updates the column values of one table with the column of another tabl
2 min read
Using CASE in ORDER BY Clause to Sort Records By Lowest Value of 2 Columns in SQL
The CASE statement in SQL is a versatile tool for implementing conditional logic within queries, similar to IF-THEN-ELSE constructs in programming languages. The ORDER BY clause in SQL is used to sort the results of a query based on one or more columns, enhancing data readability and analysis. In this guide, we'll explore how to use the CASE statem
3 min read
Stored Procedures classification based on Input and Output Parameters in SQL Server
Stored Procedure: The stored procedure has the following key points as follows. It is a collection of SQL statements such as if you want to write and read data from a database then you can use create a statement for write and select statement for reading the data from database and SQL command logic for the same, which is compiled and stored on the
2 min read
SQL Query to DELETE Certain Rows Based on Comparisons with Other Tables
In this article, we will see, how to delete certain rows based on comparisons with other tables. We can perform the function by using a subquery in place of the condition in WHERE Clause. A subquery is a query that appears inside another query. It can also be called a nested query. Syntax: SELECT * FROM table_name WHERE column_name= ( SELECT column
2 min read
SQL Query to Update From One Table to Another Based on an ID Match
In this article, we will see, how to update from one table to another table based on ID match. We can update the table using UPDATE statement in SQL. The update statement is always followed by the SET command. The SET command is used to specify which columns and values need to be updated in a table. UPDATE syntax: UPDATE table_name SET column_name
2 min read
Article Tags :