Practical - 4
Use of Simple select statement, select distinct, where and order by.
SELECT Statement:
The SELECT statement is used to select data from a database. It is used to retrieve data from
one or more tables in a database.
Syntax:
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from.
The table_name represents the name of the table you want to select data from.
Example:
Input:
Output:
Select ALL columns:
If you want to return all columns, without specifying every column name, you can use the
SELECT *
Syntax:
SELECT * FROM table_name; Example:
Input:
Output:
SELECT DISTINCT Statement:
The SELECT DISTINCT statement is used to return only distinct (different) values.
Syntax:
SELECT DISTINCT column1, column2,…
FROM table_name; Example:
Output:
SELECT Example Without DISTINCT:
If you omit the DISTINCT keyword, the SQL statement returns the "Last name" value from all
the records of the "STUDENT" table.
Syntax:
SELECT LNAME FROM Student; Example:
Input:
Output:
WHERE Clause:
The WHERE clause is used to filter records. It is used to extract only those records that fulfill
a specified condition. Syntax: SELECT column1, column2,… FROM table_name WHERE
condition; Example:
Input:
Output:
SQL ORDER BY:
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
SELECT column1, column2,…
FROM table_name
ORDER BY column1, column2,….ASC|DESC; Example:
Input:
Output:
DESC:
The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in descending order, use the DESC keyword.
Syntax:
SELECT * FROM table_name
ORDER BY column_name DESC; Example:
Input:
Output:
Order Alphabetically:
For string values the ORDER BY keyword will order alphabetically.
Syntax:
SELECT * FROM table_name
ORDER BY column_name; Example:
Input:
Output:
Alphabetically DESC:
To sort the table reverse alphabetically, use the DESC keyword:
Syntax:
SELECT * FROM
table_name ORDER BY
column_name DESC; Example:
Input:
Output:
ORDER BY Several Columns:
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" and the "CustomerName" column. This means that it orders by Country, but if some
rows have the same Country, it orders them by CustomerName.
Syntax: SELECT * FROM Customers ORDER BY Country, CustomerName; Example:
Input:
Output:
Using Both ASC and DESC:
Syntax:SELECT * FROM table_name ORDER BY column_name,… DESC; Example:
Input:
Output: