The Wayback Machine - http://web.archive.org/web/20240926113028/https://www.geeksforgeeks.org/sql-select-query/
Open In App

SQL SELECT Query

Last Updated : 10 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The SQL SELECT Statement retrieves data from a database.

SELECT Statement in SQL

The SELECT statement in SQL is used to fetch or retrieve data from a database. It allows users to access the data and retrieve specific data based on specific conditions.

We can fetch either the entire table or according to some specified rules. The data returned is stored in a result table. This result table is also called the result set. With the SELECT clause of a SELECT command statement, we specify the columns that we want to be displayed in the query result and, optionally, which column headings we prefer to see above the result table.

The SELECT clause is the first clause and is one of the last clauses of the select statement that the database server evaluates. The reason for this is that before we can determine what to include in the final result set, we need to know all of the possible columns that could be included in the final result set.

Syntax

The syntax for the SELECT statement is:

SELECT column1,column2…. FROM table_name ;

SELECT Statement Example

Let’s look at some examples of the SQL SELECT statement, to understand it better.

Let’s create a table which will be used in examples:

CREATE TABLE:

CREATE TABLE Customer(
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age int(2),
Phone int(10)
);
-- Insert some sample data into the Customers table
INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age, Phone)
VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),
(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),
(3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),
(4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),
(5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain','22','xxxxxxxxxx');

Output:

create table

Retrieve Data using SELECT Query

In this example, we will fetch CustomerName, LastName from the table Customer:

Query:

SELECT CustomerName, LastName FROM Customer;

Output:

output table

Fetch All Table using SELECT Statement

In this example, we will fetch all the fields from the table Customer:

Query:

 SELECT * FROM Customer;

Output:

fetch all field of the table

SELECT Statement with WHERE Clause

Suppose we want to see table values with specific conditions then WHERE Clause is used with select statement. 

Query:

SELECT CustomerName FROM Customer where Age = '21'; 

Output:

select statement with where clause example output

SQL SELECT Statement with GROUP BY Clause

In this example, we will use SELECT statement with GROUP BY Clause

Query:

SELECT COUNT (item), Customer_id FROM Orders GROUP BY order_id;  

Output:

sql select statement with group by clause example output

SELECT Statement with HAVING Clause

Consider the following database for HAVING Clause:

demo table

Query:

SELECT Department, sum(Salary) as Salary
FROM employee
GROUP BY department
HAVING SUM(Salary) >= 50000;

Output:

select statement with having clause example output

SELECT Statement with ORDER BY clause in SQL

In this example, we will use SELECT Statement with ORDER BY clause

Query:

SELECT * FROM Customer ORDER BY Age DESC;  

Output:

select statement with order by clause in sql

Important Points with SQL SELECT Statement

  • It is used to access records from one or more database tables and views.
  • The SELECT statement retrieves selected data based on specified conditions.
  • The result of a SELECT statement is stored in a result set or result table.
  • The SELECT statement can be used to access specific columns or all columns from a table.
  • It can be combined with clauses like WHERE, GROUP BY, HAVING, and ORDER BY for more refined data retrieval.
  • The SELECT statement is versatile and allows users to fetch data based on various criteria efficiently.

Previous Article
Next Article

Similar Reads

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
SQL | Query to select NAME from table using different options
Let us consider the following table named "Geeks" : G_ID FIRSTNAME LASTNAME DEPARTMENT 1 Mohan Arora DBA 2 Nisha Verma Admin 3 Vishal Gupta DBA 4 Amita Singh Writer 5 Vishal Diwan Admin 6 Vinod Diwan Review 7 Sheetal Kumar Review 8 Geeta Chauhan Admin 9 Mona Mishra Writer SQL query to write “FIRSTNAME” from Geeks table using the alias name as NAME.
2 min read
SQL Query to select Data from Tables Using Join and Where
The aim of this article is to make a simple program to Join two tables using Join and Where clause using MySQL. Below is the method to do the same using MySQL. The prerequisites of this article are MySQL and Apache Server on your computer are installed. What is a Query in SQL? A SQL query is a request passed for data/information from a table in a d
3 min read
SQL Query to Select all Records From Employee Table Where Name is Not Specified
Here, we are going to see how to find the names of the persons other than a person with a particular name SQL. In this article, we will be making use of the MSSQL Server as our database. For example, if the employee name is Pradeep you need to show the table of employees excluding that employee with the name Pradeep. So let us execute this query in
2 min read
SQL Query to Add Email Validation Using Only One Query
In this article let us see how can we check for the validation of mails in the student database using MSSQL as the database server. For example, if the email is like abcdedfABCDEF...0123456@gmail.com this is the valid form of an email if it is other than this then that is said to Invalid. So, now we will discuss this concept in detail step-by-step:
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
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
SQL Query to Check if Date is Greater Than Today in SQL
In this article, we will see the SQL query to check if DATE is greater than today's date by comparing date with today's date using the GETDATE() function. This function in SQL Server is used to return the present date and time of the database system in a ‘YYYY-MM-DD hh:mm: ss. mmm’ pattern. Features: This function is used to find the present date a
2 min read
SQL Query to Add a New Column After an Existing Column in SQL
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve data from relational databases like MySQL, Oracle, SQL Server, Postgres, etc. In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modif
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
PHP | MySQL Select Query
The SQL SELECT statement is used to select the records from database tables. Syntax : The basic syntax of the select clause is - To select all columns from the table, the [TEX] * [/TEX] character is used. Implementation of the Select Query : Let us consider the following table ' Data ' with three columns ' FirstName ', ' LastName ' and ' Age '. To
3 min read
Python MariaDB - Select Query using PyMySQL
MariaDB is an open source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python. In this article we will look into the process of querying data from a table of the database using pymysql. To query data use the following syntax: Syntax : In order to sele
2 min read
SQLite SELECT Query
SQLite is a serverless, popular, easy-to-use, relational database system that is written in c programming language. SQLite is a database engine that is built into all the popular devices that we use every day of our lives including TV, Mobile, and Computer. As we know that we create the tables in the database and insert the data into them to store
6 min read
MySQL Query to Select Top 10 Records?
Each row in the Customers table represents a unique customer and contains various details about them. One of these details is the customer’s Order_Val, which represents the total value of all orders that the customer has placed. Your task is to write an SQL query that selects information about the top 10 customers who have the highest order values.
4 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 vs NO SQL vs NEW SQL
SQL stands for Structured Query Language. Which is based on relational algebra and schema is fixed in this which means data is stored in the form of columns and tables. SQL follows ACID properties which means Atomicity, Consistency, Isolation, and Durability are maintained. There are three types of languages present in SQL : Data Definition Languag
2 min read
Select top in MS SQL Server
Prerequisite - Select in MS SQL Server Suppose that a user wants to extract the top students from the whole institution but has to use some complex queries to extract the data. To avoid complexity, the user can use 'Select Top'. 'Select Top' extracts the limited number of rows. This results in accurate data along with less time consumption. Syntax
2 min read
SELECT data from Multiple Tables in SQL
The statement is used to retrieve the fields from multiple tables and with the help of JOIN operations we easily fetch the records from multiple tables, Generally JOINS are used when there are common records between two tables. In this article, we will look into various types of JOIN that are used in SQL. SQL JoinsSQL joins combine two or more tabl
3 min read
SQL - SELECT DATE
In Microsoft SQL Server, SELECT DATE is used to get the data from the table related to the date, the default format of date is 'YYYY-MM-DD'. Syntax: SELECT * FROM table_name WHERE condition1, condition2,..; Now we will execute queries on SELECT DATE on database student in detail step-by-step: Step 1: Creating a database university: CREATE DATABASE
1 min read
SQL - SELECT RANDOM
RANDOM( ) in SQL is generally used to return a random row from a table present in the database. It has many applications in real life. For example : There are a lot of employees in an organization. Suppose, if the event manager wants to mail any ten random employees then he/she can use the RANDOM( ) in SQL to get the Email Id of the ten random empl
2 min read
SQL - SELECT NULL
The word NULL is used to describe a missing value in SQL. In a table, a NULL value is a value in a field that appears to be empty. A field with a NULL value is the same as one that has no value. It's important to grasp the difference between a NULL value and a zero value or a field of spaces. There are two possibilities: Where SQL is NULLSyntax: SE
2 min read
How to Select All Records from One Table That Do Not Exist in Another Table in SQL?
We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries. In this let us see How to select All Records from One Table That Do Not Exist in Another Table step-by-step. Creating a Database Use the below command to create a database named Geeks
2 min read
How to Select Words With Certain Values at the End of Word in SQL?
To select words with certain values at the end of the word In SQL, we can use pattern matching. A pattern matching allows users to search for certain patterns in the data. It is done using the LIKE operator in SQL. The query uses wildcard characters to match a pattern, Wildcard characters are case-sensitive. Some wildcard characters and their meani
2 min read
How to Exclude Records With Certain Values in SQL Select?
In this article, we will understand how to exclude some records having certain values from a table. For the purpose of demonstration, we will be creating a Participant table in a database called “GeeksForGeeksDatabase“. Step 1: Creating the DatabaseUse the below SQL statement to create a database called GeeksForGeeksDatabase. Query: CREATE DATABASE
3 min read
How to Select Group of Rows that Match All Items on a List in SQL Server?
In this article, we will see, how to select a group of rows that match all the items on a list in SQL Server. We can perform the above function by two methods. Those are: By using IN operatorBY performing JOIN using STRING_SPLIT methodIN operator: It allows you to specify a list of values in a WHERE clause. STRING_SPLIT(): this function can be used
2 min read
How to Select a Range of Letters in SQL?
In this article, we will see how to Select a Range of Letters in SQL using the LIKE clause. The LIKE clause is used for pattern matching in SQL using wildcard operators such as %, ^, etc. It has square brackets[] as one of the wildcard operators that is used to specify the range of characters for pattern matching. Let see these above mention functi
2 min read
How to Use SELECT In Order BY Specific Ids in SQL?
The order by the statement is used in SQL to sort the result set in ascending or descending by mentioning it in the suffix as DESC (for descending) and for ASC(for ascending). In this article, we will be doing order by on a database with some specified values of the column only. So let's start by creating a Database first. Step 1: Create a database
1 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
How to Use SELECT With Aggregate Functions in SQL?
In SQL, mainly five aggregate functions are provided. These help us to process the table data in the desired way. All these are 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 create a database named GeeksForGeeks. Query: CREATE DATABASE Gee
2 min read
How to Select Data Between Two Dates and Times in SQL Server?
In SQL, some transactions need to be extracted based on their completion times and dates. Here, the DATETIME2 data type in SQL to perform such operations. For this article, we will be using the Microsoft SQL Server as our database. Note: Here, we will use the two dates and times given in the query and separate them using the BETWEEN keyword. This i
2 min read