How To Select From One Table in SQL

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:

  1. =: Equal
  2. <>: Not equal
  3. !=: Not Equal
  4. >: Greater than
  5. <: Less than
  6. >=: Greater than or equal
  7. <=: Less than or equal
  8. BETWEEN: Between an inclusive range
  9. LIKE: Search for a pattern
  10. 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;

 

Subscribe for Free Updates

Please enable the javascript to submit this form