Friday, November 20, 2015

SQL Like and Distinct Command

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
1John28
2Alex24
3James35
4Roy22
5Kay44

select * from employee where employee_name like 'J%'
The result of the above given query is given below.
mployee_IDEmployee_NameAge
1John28
3James35

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
3James35
5Kay44

To fetch all names ending with letter y, following SQL query is used.
select * from employee where employee_name like '%y'
Employee_IDEmployee_NameAge
4Roy22
5Kay44

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
Item15400102000
Item26300101800
Item3315545
Item4230560
Item523005600
Item66400102400

Following SQL query is used to fetch unique prices from sales table.
select distinct(price) prices from SALES
Price
400
300
15
30

No comments: