SQL SELECT Statement

What is the SELECT Statement?

The SELECT statement in SQL is used to retrieve data from one or more tables. It allows you to specify which columns of data you want to view from the database. You can also filter and sort the results.

The basic syntax for the SELECT statement is:

SELECT column1, column2, ...
FROM table_name;

If you want to select all columns from the table, you can use the wildcard *:

SELECT * FROM table_name;

Example: Customers Table

Consider the following Customers table:

CustomerID FirstName LastName Email Phone
1 MOHD Zaid MOHD.Zaid@example.com 555-1234
2 Mujtaba Khan Mujtaba.Khan@example.com 555-5678
3 Akef Khan Akef.Khan@example.com 555-9876

Retrieving Data Using SELECT

To retrieve all the records from the Customers table, use the following SQL query:

SELECT * FROM Customers;

This query returns all columns and rows from the Customers table.

Selecting Specific Columns

If you only want to select specific columns, you can list the column names. For example, to retrieve the first name, last name, and email of customers, use the following query:

SELECT FirstName, LastName, Email
FROM Customers;

Filtering Results Using WHERE Clause

You can filter the results of a query by using the WHERE clause. For example, to retrieve the details of the customer whose CustomerID is 1, you can write:

SELECT * FROM Customers
WHERE CustomerID = 1;

Sorting Results Using ORDER BY

You can sort the results of a query using the ORDER BY clause. For example, to retrieve all customers and sort them by their last name in ascending order, use the following query:

SELECT * FROM Customers
ORDER BY LastName ASC;

To sort in descending order, you would use DESC instead of ASC.