0% found this document useful (0 votes)
7 views10 pages

Basic Operations With MySQL - Part 3

The document provides an overview of MySQL conditions, focusing on logical operators such as AND, OR, and NOT, as well as LIKE, IN, and BETWEEN conditions for filtering records. It also covers aggregate functions, string functions, SQL aliases, and grouping data using the GROUP BY statement. Examples are included to illustrate the syntax and usage of these SQL features.

Uploaded by

entcules849567
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
7 views10 pages

Basic Operations With MySQL - Part 3

The document provides an overview of MySQL conditions, focusing on logical operators such as AND, OR, and NOT, as well as LIKE, IN, and BETWEEN conditions for filtering records. It also covers aggregate functions, string functions, SQL aliases, and grouping data using the GROUP BY statement. Examples are included to illustrate the syntax and usage of these SQL features.

Uploaded by

entcules849567
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 10

MySQL Conditions

LOGICAL OPERATORS

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
is 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.

The AND operator displays a record if both the first condition and the second
condition is true.

The OR operator displays a record if either the first condition or the second
condition is true.

The NOT operator none of would be selected.

AND Condition
AND condition is used with SELECT, INSERT, UPDATE or DELETE
statements to test two or more conditions in an individual query. Here the
operation will be performed only on those records which satisfies all the
conditions.
If any of the conditions evaluates to false, then those records will not be
selected for the operation (SELECT, INSERT, UPDATE or DELETE).

Syntax:
WHERE condition1
AND condition2
...
AND condition_n;

Example: Display the details of the customer whose fname is Ajeet and
cus_ID is 3.
SELECT * FROM Customer
WHERE fname = 'Ajeet' AND cus_id > 3;
OR Condition
The MySQL OR condition specifies that if you take two or more conditions then
one of the conditions must be fulfilled to get the records as result.

SYNTAX:

WHERE condition1
OR condition2
...
OR condition_n;

Example: Display the details of the customer whose fname is Ajeet OR


cus_ID is 3.

SELECT * FROM Customer


WHERE fname = 'Ajeet' OR cus_id > 3;

AND & OR condition

We can use AND & OR condition both together with the SELECT,
INSERT, UPDATE and DELETE statement. While combine these
conditions, you must be aware where to use round brackets so that the
database know the order to evaluate each condition.

Syntax:

WHERE condition1
AND condition2
...
OR condition_n;

Example: Consider the following table.

Execute the following query:


SELECT * FROM students
WHERE ( course_name = 'Java' AND student_name = 'Aryan')
OR (student_id > 5);

Output:

LIKE condition

LIKE condition is used to perform pattern matching to find the correct


result. It is used in SELECT, INSERT, UPDATE and DELETE statement
with the combination of WHERE clause.

Syntax:

columnname LIKE pattern [ ESCAPE 'escape_character' ]

Parameters:
• expression: It specifies a column or field.
• pattern: It is a character expression that contains pattern
matching.
• escape_character: It is optional. It allows you to test for literal
instances of a wildcard character such as % or _. If you do not
provide the escape_character, MySQL assumes that "\" is the
escape_character.

• 1) Using % (percent) Wildcard:


% represents zero or more characters. It is usually used as a
pattern matching expression.

Example# 1: Display the name of the customers whose names


begin with ‘A’.
SELECT name FROM Customers

WHERE name LIKE 'A%';

Example # 2: Display the details of the products ending with


‘th’ from Products table.

SELECT * FROM Products

WHERE pname LIKE '%th';


• 2) Using _ (Underscore) Wildcard:
The _ ( Underscore ) wildcard character represents a single
character.

Example: Display the details of the Products whose names has a


second character as ‘a’.

SELECT * FROM Products


WHERE pname LIKE '_a%';

• 3) Using NOT Operator:


We can also use NOT operator with MySQL LIKE condition. This
example shows the use of % wildcard with the NOT Operator.

Example: Display the names of the Employees whose names do


not end with ‘h’.

SELECT name FROM Employees

WHERE name NOT LIKE '%h';

IN and NOT IN Condition


IN condition is used to reduce the use of multiple OR conditions in a SELECT,
INSERT, UPDATE and DELETE statement.

Syntax:

Columnname IN (value1, value2, .... value_n);

where, value1, value2, ... or value_n: These are the values to test against
expression. If any of these values matches expression, then the IN
condition will evaluate to true. This is a quick method to test if any one
of the values matches expression.

Example: Display the details of employees with employee ID E101, E105


and E106.

SELECT * FROM Employees

WHERE Emp_id IN (‘E101’, ‘E105’, ‘E106’);

The above query can also be written using OR clause as

SELECT * FROM Employees


WHERE Emp_id =‘E101’ OR

Emp_id= ‘E105’ OR Emp_id ‘E106’;

Example: Selects all employees that are NOT located in "Germany",


"France" or "UK".

SELECT * FROM Employees


WHERE Country NOT IN ('Germany', 'France', 'UK');

RANGE SEARCHING

The BETWEEN operator selects a range of data between two values. The
values can be numbers, text, or dates.

Syntax:
SELECT column_name FROM table_name

WHERE column_name BETWEEN value1 AND value2;

Example: Display the productno, name profit and selling price from
Product_master table, where profits between 500 and 800.

Select productno, name, profit, sellprice FROM product_master

Where profit BETWEEN 500 AND 800;

Example: Display the productno, name, profit and selling price whose
profits is other than the range 100 and 350.

Select productno, name, profit sellprice FROM product_master

Where profit NOT BETWEEN 100 AND 350;

Example: Display the details of the products with price between 10000
and 20000 of vendors other than HP, Vivo and Nokia

SELECT * FROM Products

WHERE(Price BETWEEN 10000 AND 20000) AND

NOT vendor IN (‘hp’,’vivo’,’nokia’);

AGGREGATE FUNCTIONS
MATH BASED FUNCTIONS

• AVG - returns average value of expr. This function takes as an


argument any numeric data type or any nonnumeric data type
that can be implicitly converted to a numeric data type.
SELECT AVG (salary) "Average" FROM employees;

• MAX - returns maximum value of expr


The following example determines the highest salary in the
employees table: SELECT MAX (salary) "Maximum" FROM
employees;

• MIN - returns minimum value of expr.


The following statement returns the earliest hire date in the
employees table: SELECT MIN (hire_date) "Earliest" FROM
employees;

• SUM - returns the sum of values of expr.


The following example calculates the sum of all salaries in the
employees table:
SELECT SUM (salary) "Total" FROM employees;

• Count (expr) - The COUNT (expr) function returns the number


of rows that matches specified criteria and returns the number
of rows where expr is not null.
SELECT COUNT (ProductID) FROM Products;

• Count(*) - Returns the number of rows in the table including


duplicates and those with null
Select count (*) “total” from client_master;

• Abs(n) - Returns the absolute value of n


Select ABS (-15) from dual; Results in 15

• Power(m,n) - Returns m raised to the power of n. n must be


integer else an error occurs.
Select power(3,2) from dual;
Results in 9
• Round(n,m) - Returns n rounded to m place of the decimal
point. if m is omitted to zero places m can be negative to round
of digits left of the decimal point. m must be an integer.
Select round (15.19, 1) form dual;
Results in 15.2

• Sqrt(n) - Returns square root of n. If n<0 NULL. Sqrt return a


real result.
Select sqrt(25) from dual;
Results in 5

STRING BASED FUNCTIONS

• Lower(char) - Returns character with all case in lower letters.


Select lower(‘MUMBAI’) From Dual;
Results in Mumbai

• INTCAP(char) - Returns string with first letter in uppercase


character.
Select INTCAP(‘god’) form dual; Results in God

• upper(char)
Returns character with all case in upper case letters.
Select upper(‘welcome’) From Dual; Results in WELCOME

• SUBSTR(char, m,n) - Returns a portion of the char. Beginning


at character m, and n character long (if n is omitted, to the end
of the character) the first portion of the character is 1.
Select substr(‘freedom’,1,4) form dual; Results in free

• length(char) - returns the length of the character.


Select length(‘independence’) from dual; Results in 12

• RTRIM() - function removes any trailing blanks from a string or


column.
SQL> SELECT RTRIM('Opal Kole2254', '2254') "RTRIM"
FROM DUAL;
RTRIM
---------
Opal Kole

• LTRIM() - removes blanks from the beginning of a string instead


of end.
SQL> SELECT LTRIM ('2254Opal Kole', '2254') "LTRIM"
FROM DUAL;
LTRIM
---------
Opal Kole

• To_number(char) - TO_NUMBER converts expr to a value of


NUMBER datatype. The expr can be a value of CHAR,
VARCHAR2.

UPDATE employees
SET salary = salary + TO_NUMBER('100.00','9G999D99')
WHERE last_name = 'Perkins';

• To_date() - The Oracle/PLSQL TO_DATE function converts a


string to a date. The syntax for the TO_DATE function in
Oracle/PLSQL is:

TO_DATE( string1 [, format_mask] [, nls_language] )

Example:

TO_DATE('2003/07/09', 'yyyy/mm/dd')

Result: date value of July 9, 2003

TO_DATE('070903', 'MMDDYY') Result: date value of July 9, 2003


TO_DATE('20020315', 'yyyymmdd') Result: date value of Mar 15, 2002

SELECT TO_DATE('2015/05/15 8:30:25', 'YYYY/MM/DD HH:MI:SS')


FROM dual;

SQL ALIASES

SQL aliases are used to give a table or a column in a table, a temporary


name.
Aliases are often used to make column names more readable. An alias
only exists for the duration of the query.

The following SQL statement selects all the orders from the customer
with CustomerID=4. We use the "Customers" and "Orders" tables, and
give them the table aliases of "c" and "o" respectively (Here we use aliases
to make the SQL shorter):

Example:

SELECT O.OrderID, O.OrderDate, C.CustomerName


FROM Customers AS C, Orders AS O
WHERE C.CustomerName="sam"AND C.CustomerID=O.CustomerID;

Aliases can be useful when:


• There are more than one table involved in a query
• Functions are used in the query
• Column names are big or not very readable
• Two or more columns are combined together

GROUPING DATA FROM TABLES IN SQL

The grouping of data is possible with GROUP BY statement is often used


with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the
result-set by one or more columns.

Consider the following table SalesOrder


orderno productno qtyOrdered
19001 1001 10
19001 3453 3
19001 6734 3
46865 6734 4
46865 3453 10
46865 1001 2
73965 3453 2
73965 1001 1
73965 6734 1
1. Select product no total quantity ordered for each product .
SELECT productno, sum (qtyOrdered)“TOTAL”
FROM SalesOrder GROUP BY productno;
Result:
productno TOTAL
1001 13
3453 15
6734 8

2. Select productno total quantity ordered for productno 1001 and 3453.
Select productno, SUM(qtyOrdered) “TOTAL”
FROM SalesOrder
GROUP BY productno
HAVING productno=1001 AND productno=3453;
Result:
productno TOTAL
1001 13
3453 15



You might also like