Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
62 views

LAB 04 Basic Queries (Part 2) : IN Operator

This document discusses various SQL operators and functions including IN, BETWEEN, LIKE, UNION, and ORDER BY. It provides examples of how to use each with sample queries and expected results. The key points covered are: - The IN operator allows selecting values from a list using a WHERE clause. - BETWEEN selects values within a range, similar to >= and <=. - LIKE performs pattern matching with wildcards. - UNION combines result sets from multiple queries into one result set. - ORDER BY sorts the results of a query in ascending or descending order. - Functions like LEFT() and aliases can be used to derive new attributes for selection.

Uploaded by

Thiệp Lê
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

LAB 04 Basic Queries (Part 2) : IN Operator

This document discusses various SQL operators and functions including IN, BETWEEN, LIKE, UNION, and ORDER BY. It provides examples of how to use each with sample queries and expected results. The key points covered are: - The IN operator allows selecting values from a list using a WHERE clause. - BETWEEN selects values within a range, similar to >= and <=. - LIKE performs pattern matching with wildcards. - UNION combines result sets from multiple queries into one result set. - ORDER BY sorts the results of a query in ascending or descending order. - Functions like LEFT() and aliases can be used to derive new attributes for selection.

Uploaded by

Thiệp Lê
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

LAB 04

BASIC QUERIES (PART 2)

❖ Main contents
- How to use some operators such as IN, BETWEEN, UNION, LIKE, ORDER BY;
- Derived Attribute

1. IN operator

IN operator allows selecting the value from a set of values. The syntax used is as follows:

SELECT list of column


FROM table name
WHERE column IN ("value 1","value 2"…)
The columns in the WHERE clause do not need to appear in the selected column list, but it must
be a column in the table. If the list has more than one value, each item is separated by a comma.
Besides, the NOT operator may be used with the IN operator for negative purposes.

Let's take a look at some examples:

Suppose if we want to find all offices located in USA and France, we can execute the
following query:

SELECT officeCode, city, phone


FROM offices
WHERE country = 'USA' OR country = 'France';

In this case, we can use IN instead of the above query:

SELECT officeCode, city, phone


FROM offices
WHERE country IN ('USA','France');

Result:
To obtain all offices note located in the USA and France, we can use NOT IN as follows:

SELECT officeCode, city, phone


FROM offices
WHERE country NOT IN ('USA','France');

Result:

2. BETWEEN operator

BETWEEN operator allows taking values within a specific range. It must be used in the WHERE
clause. The following illustrates the syntax:

SELECT column_list
FROM table_name
WHERE column_1 BETWEEN lower_range AND upper_range;

MySQL returns all records in which the column_1 value is in the lower_rage and upper_range
ranges. The equivalent query to get the same result is:

SELECT column_list
FROM table_name
WHERE column_1 >= lower_range AND column_1 <= upper_range;

Example:
Assuming we want to find all products priced between $ 90 and $ 100, we can execute the
following query:
SELECT productCode, ProductName, buyPrice
FROM products
WHERE buyPrice BETWEEN 90 AND 100
ORDER BY buyPrice DESC;

Result:

To find all records that are not in a range, we use NOT BETWEEN. For example, to find all
products with purchase prices outside the 20 and 100 ranges, we could use the following query:

SELECT productCode, ProductName, buyPrice


FROM products
WHERE buyPrice NOT BETWEEN 20 AND 100;

Result:

The above query is equivalent to the following query:

SELECT productCode, ProductName, buyPrice


FROM products
WHERE buyPrice < 20 OR buyPrice > 100
ORDER BY buyPrice DESC;

Result:
3. LIKE operator

LIKE operator allows searching for information based on character comparisons (‘like’). LIKE
is often used with the SELECT statement in the WHERE clause. MySQL provides two wildcards
for constructing patterns, which is % and _.

• The percentage ( % ) wildcard matches any string of zero or more characters.

• The underscore ( _ ) wildcard matches any single character.

Example: Suppose we want to find employees whose first name starts with the letter 'a', it can
be done as follows:

SELECT employeeNumber, lastName, firstName


FROM employees
WHERE firstName LIKE 'a%';

Result:

MySQL scans the entire employees table to find all employees whose first names start with
the letter 'a' and are followed by any number of characters.

Example: Find all employees whose last name end with the string ‘on’, we can execute the
following query:

SELECT employeeNumber, lastName, firstName


FROM employees
WHERE lastName LIKE '%on';

Result:
If we only know that the search string is embedded inside in the middle of a string, you can set
the beginning and the end of the pattern with the percentage wildcard (%) to find all possibilities.

Example: Get all the employees whose last names contain “on”, we can execute the following
query:

SELECT employeeNumber, lastName, firstName


FROM employees
WHERE lastName LIKE '%on%';

Result:

The MySQL allows you to combine the NOT operator with the LIKE operator to find a string
that does not match a specific pattern.
Example: Get employees whose last names don’t start with the character 'B', execute as
follows:

SELECT employeeNumber, lastName, firstName


FROM employees
WHERE lastName NOT LIKE 'B%';

Result:
Note: When searching for partial strings in MySQL with LIKE you will match case-insensitive
(not case-sensitive) by default, so ‘b%’ and ‘B%’ are the same.
Sometimes the pattern, which you want to match, contains wildcard character e.g., 10%, _20,
etc. In this case, you can use the ESCAPE clause to specify the escape character so that MySQL
will interpret the wildcard character as a literal character. If you don’t specify the escape
character explicitly, the backslash character \ is the default escape character.
Example: Find products whose code contains the string ‘_20’, then execute the query as
follows:

SELECT productCode, productName


FROM products
WHERE productCode LIKE '%\_20%';

Result:
LIKE provides a convenient way to find records whose columns contain strings that match the
search pattern. However, because the LIKE implementation is to scan the entire table to find all
matching records so it does not allow the database engine to use the index to search quickly.
When the data in the table is large enough, LIKE performance will be degraded. In some cases,
this problem can be avoided by using other techniques to achieve equivalent results. Or use
MySQL's FULLTEXT indexing method (will discuss this technique in the course of MySQL
Database Management System).

Example: if looking for all the staff have first names beginning with a string specified using
the LEFT() function like the following query:

SET @str = 'b';


SELECT employeeNumber, lastName, firstName
FROM employees
WHERE LEFT(lastname, length(@str)) = @str;

Result:

The result of this query is equivalent to the following query, but the performance of the
following clause is much better because we can use the index on the lastname column.

SELECT employeeNumber, lastName, firstName


FROM employees
WHERE lastname LIKE 'b%';
4. Derived Attribute
SQL provides the ability to create Derived Attribute in the result table by using operators and
functions based on available attributes. Column names of Derived Attribute depend on systems,
but alias can be assigned as column names.
The following example creates an derived attribute column named lineTotal, which is the
result of the multiplication between priceEach and quantityOrdered properties.

SELECT orderNumber, (priceEach*quantityOrdered) as lineTotal


FROM orderdetails;

5. Sort the results with ORDER BY


ORDER BY clause allows you to sort the results in one or more columns of the query results in
ascending or descending order. To sort results in ascending order, use ASC; descending is DESC.
By default, ORDER BY will sort the results in ascending order.

Example: To sort the employee list by name and job title, the following query can be executed:

SELECT FirstName, LastName, jobtitle


FROM Employees
ORDER BY firstname ASC, jobtitle DESC;
Or, we can provide information about product names in ascending order of inventory by
querying as follows:
SELECT productName
FROM Products
ORDER BY quantityInStock;
In the statement above, the ASC keyword is not used, because by default, the results will be
sorted in ascending order. The result of the statement in the following figure.

If it is not specified if sorting is executed in ascending or descending order, MySQL will default
to the data sorting in ascending order.
6. Combine the results with UNION operator

UNION operator allows combining two or more result sets from multiple tables together. The
syntax of using MySQL UNION is as follows:

SELECT statement
UNION [DISTINCT | ALL]
SELECT statement
UNION [DISTINCT | ALL]

To use UNION, there are a few guidelines to follow:


• The number of columns in each SELECT statement must be the same.
• The data types of the column in the column list of the SELECT statement must be the
same or at least convertible to each other.

By default, UNION MySQL removes all duplicate rows from the results even if the
DISTINCT keyword is not used after the UNION keyword.

If using UNION ALL, the duplicate rows remain in the final result set. This should only be used
in cases where either you want to keep duplicates of rows, or make sure that there are no
duplicate rows in the result set.
Example: To combine information about customers and employees into a result set, use the
following query:

SELECT customerNumber id, contactLastname name


FROM customers
UNION
SELECT employeeNumber id, firstname name
FROM employees;
When using ORDER BY to sort results with UNION, it must be placed at the last position in the
SELECT statement.

Example: Assuming a combination of employee and customer information, then want to sort
the results by name and ID in ascending order

(SELECT customerNumber, contactLastname


FROM customers)
UNION
(SELECT employeeNumber, firstname
FROM employees)
ORDER BY contactLastname, customerNumber;
If the column names are not the same in the two SELECT statements of the UNION operation,
which names will be displayed at the output if we do not use aliases for each column in the
SELECT clause. The answer is that MySQL will use the column names of the first SELECT
statement as the column names in the output.

(SELECT customerNumber, contactLastname


FROM customers)
UNION
(SELECT employeeNumber, firstname
FROM employees)
ORDER BY contactLastname, customerNumber;

The result of the mathematical operation between the two result sets from the customers and
employees data table.
MySQL also provides another option to sort the result set based on the column position in the
ORDER BY clause as follows:

(SELECT customerNumber, contactLastname


FROM customers)
UNION
(SELECT employeeNumber, firstname
FROM employees)
ORDER BY 2, 1;
❖ Practical exercises

1. Use the IN operator to find customers living in Nantes and Lyon. Write another way
using the OR operator.

2. Use BETWEEN to find orders shipped between January 10, 2003 and March 10, 2003.
Write another way using the AND operator.

3. Use LIKE to get product lines that its name contain the word ‘CARS’.

4. Get 10 products with the largest quantity in stock.

You might also like