Lesson 1: Some Fields
The SELECT statement is used to select data from a database. The data returned is stored in a result table.
SELECT column1, column2 FROM table_name;
Lesson 2: All Fields
If you want to select all the fields available in the table,
SELECT * FROM table_name;
Lesson 3: Distinct Values
The SELECT DISTINCT statement is used to return only distinct or different values. Inside a table, a column often contains many duplicate values and sometimes you only want to list the distinct values.
SELECT DISTINCT column1, column2 FROM table_name;
Lesson 4: Filter based on Condition
The WHERE clause is used to filter records. It is used to extract only those records that meets a specified condition.
SELECT column1, column2 FROM table_name WHERE condition;
The following operators can be used in the WHERE clause:
- =: Equal
- <>: Not equal
- !=: Not Equal
- >: Greater than
- <: Less than
- >=: Greater than or equal
- <=: Less than or equal
- BETWEEN: Between an inclusive range
- LIKE: Search for a pattern
- IN: To specify multiple possible values for a column
Lesson 5: Multiple Conditions
The WHERE clause can be combined with AND, OR, and NOT operators. The AND and OR operators are used to filter records based on more than one condition.
The AND operator displays a record if all the conditions separated by AND is TRUE.
SELECT column1, column2 FROM table_name WHERE condition1 AND condition2;
The OR operator displays a record if any of the conditions separated by OR is TRUE.
SELECT column1, column2 FROM table_name WHERE condition1 OR condition2;
The NOT operator displays a record if the condition is NOT TRUE.
SELECT column1, column2 FROM table_name WHERE NOT condition;
You can also combine the AND, OR and NOT operators.
Lesson 6: Sorting Ascending or Descending
The ORDER BY keyword is used to sort the result-set in ascending or descending order. It sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
SELECT column1, column2 FROM table_name ORDER BY column1, column2 DESC;
Lesson 7: Limit Number of Records
The LIMIT clause is used to specify the number of records to return. It is useful on large tables with thousands of records. Returning a large number of records can impact performance.
SELECT column_names FROM table_name WHERE condition ORDER BY column1 LIMIT number;