Basic SQL Queries
SQL stands for Structured Query Language which is a RDB(Relational Database). SQL lets you access and manipulate databases. Some basic SQL queries are given below:
SELECT
The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.
Syntex
Example 1 Example 2SELECT DISTINCT
The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
Syntex
Example 1The following SQL statement lists the number of different (distinct) customer countries.
Example 2 (Doesn't work on MS Access)
Example 3 (For MS Access)
WHERE
The WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition.
Syntex
Example 1 Example 2 Operators in The WHERE ClauseOperator | Description |
---|---|
= | Equal |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
<> | Not equal. Note: In some versions of SQL this operator may be written as != |
BETWEEN | Between a certain range |
LIKE | Search for a pattern |
IN | To specify multiple possible values for a column |
AND, OR and NOT
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 are TRUE.
- The OR operator displays a record if any of the conditions separated by OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.
AND Syntex
OR Syntex AND Syntex Example 1 Example 2 Example 3 Example 4 Example 5ORDER BY
The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
Syntax
Example 1 Example 2 Example 3 Example 4INSERT INTO
The INSERT INTO statement is used to insert new records in a table.
It is possible to write the INSERT INTO statement in two ways:
- Specify both the column names and the values to be inserted
- Adding values for all the columns of the table
Syntex for specified columns and values
Syntex for all columns Example 1INSERT INTO Customers
VALUES (null, 'Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
NULL
It is not possible to test for NULL values with comparison operators, such as =, <, or <>. We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntex
IS NOT NULL Syntex Example 1 Example 2UPDATE
The UPDATE statement is used to modify the existing records in a table.
Syntex
Example 1 Example 2DELETE
The DELETE statement is used to delete existing records in a table.
Syntex
Syntex for deleting all content in the table while keeping the structure Example 1 Example 2Happy Coding!