Querying data

In this topic we will learn following queries:

  1. SELECT
  2. DISTINCT
  3. WHERE clause
  4. AND, OR, NOT
  5. LIMIT
  6. LIKE
  7. IN
  8. BETWEEN

SELECT

select is used to fetch all data from a table.

Pattern:

SELECT * FROM table;

Example:

SELECT * FROM employees;

DISTINCT

Distinct is used to fetch only common data. As example, there have many common data. In our table, we have same department and designation that inserted multiple times. Now if we want to fetch common department or designation, then we will use DISTINCT keyword.

Pattern:

SELECT DISTINCT(Column) from table;

Example:

SELECT DISTINCT(Department) FROM employees;

WHERE clause

Where is used to fetch only which data we want. As example, we want data who are in the IT department. Then we will execute following query:

Pattern:

SELECT * FROM table where Column='data_yo_want_to_search'

Example:

SELECT * FROM employees WHERE Department='IT';

AND, OR, NOT

AND is used to fetch only matching data. OR is used to fetch any of data from search criteria. NOT is used to fetch data only that are not matching.

Here are examples:

AND:

SELECT * FROM employees WHERE Department='IT' AND salary='25000';

OR:

SELECT * FROM employees WHERE Department='IT' OR salary='25000';

NOT:

SELECT * FROM employees WHERE Department!='IT'

LIMIT

LIMIT is used to specify the number of records to return

Pattern:

SELECT * FROM table LIMIT number;

Example:

SELECT * FROM employees LIMIT 3;

LIKE

LIKE is used to fetch data by pattern of a character

Pattern 1:

When you want to search data which ends with your specified characters.

SELECT * FROM table WHERE Column LIKE '%N';

Example:

SELECT * FROM employees WHERE LastName LIKE '%an';

Pattern 2:

When you want to search data which starts with your specified characters.

SELECT * FROM table WHERE column LIKE 'N%';

Example:

SELECT * FROM employees WHERE LastName LIKE 'ra%';

Pattern 3:

When you want to search data whatever the characters position is.

SELECT * FROM table WHERE Column LIKE '%N%';

Example:

SELECT * FROM employees WHERE LastName LIKE '%ra%';

IN

It is used to fetch multiple data from a table.

Pattern:

SELECT * FROM table WHERE Column IN ('value1','value2',......,'valueN');

Example:

SELECT * FROM employees WHERE Department IN ('IT','Marketing');

BETWEEN

Between is used to fetch data between two values

Pattern:

SELECT * FROM table WHERE Column BETWEEN value1 AND value2;

Example:

SELECT * FROM employees WHERE Salary BETWEEN 25000 AND 30000;
about author

admin

salmansrabon@gmail.com

If you like my post or If you have any queries, do not hesitate to leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *