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;
Consider the following Customers
table:
CustomerID | FirstName | LastName | 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 |
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.
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;
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;
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
.