SQL Like and Distinct Command

    6 Votes


In this article, we will look into the Like command which is used for wild card filtering of data from a table, when used in different positions with the help of examples. Primary objective of distinct command is to fetch unique values from a given table.

SQL Like Query

For wildcard filtering “Like ” operator is used. Within a search string, % means match any number of occurrences of any character. For example, to fetch all the employees starting with letter "J" from employee table given below, following SQL query is used.

Table Name: Employee

Employee_IDEmployee_NameAge
1 John 28
2 Alex 24
3 James 35
4 Roy 22
5 Kay 44

select * from employee where employee_name like 'J%'

The result of the above given query is given below.

Employee_IDEmployee_NameAge
1 John 28
3 James 35

To fetch all names containing letter a, following SQL query is used. This query will fetch all records having letter 'a' at any position. Please note that, like query is case sensitive.

select * from employee where employee_name like '%a%'
Employee_IDEmployee_NameAge
3 James 35
5 Kay 44

To fetch all names ending with letter y, following SQL query is used.

select * from employee where employee_name like '%y'
Employee_IDEmployee_NameAge
4 Roy 22
5 Kay 44

Points to be noted before using Like Operator

SQL 'Like' search takes more time to process. So before using like operator following tips should be considered.

  • Don't overuse wildcards. If another search operator will do, use it instead.
  • When you do use wildcards, try to not use them at the beginning of the search pattern unless absolutely necessary. Search patterns that begin with wildcards are the slowest to process.
  • Pay careful attention to the placement of the wildcard symbols. If they are misplaced, you might not return the data you intended.

SQL Distinct Clause

SQL Distinct keyword is used to find unique values from specified column in a table or the number of rows that match a specific criterion. To select distinct prices from sales table given below

Table Name: Sales

ItemQuantityPriceReductionTotal
Item1 5 400 10 2000
Item2 6 300 10 1800
Item3 3 15 5 45
Item4 2 30 5 60
Item5 2 300 5 600
Item6 6 400 10 2400

Following SQL query is used to fetch unique prices from sales table.

select distinct(price) prices from SALES
Price
400
300
15
30