SlideShare a Scribd company logo
1 of 44
Download to read offline
Data Handling & Decision Making
Madhusha (Maddy) Nanayakkara
SQL & MYSQL FOR
DATA ANALYTICS
SERIES
Lesson 6
Data Manipulation with
SQL: SELECT, WHERE,
ORDER BY
Basic SELECT
Statement
SELECT
SELECT select_list
FROM table_name;
• select_list: specify one or more columns from which you
want to select data after the SELECT keyword. If the
select_list has multiple columns, you need to separate them
by a comma (,).
• table_name: specify the name of the table from which you
want to select data after the FROM keyword.
SELECT
CREATE DATABASE IF NOT EXISTS test1;
USE test1;
ALTER TABLE buyersDROP FOREIGN KEY buyers_fk;
DROP TABLE IF EXISTS buyer_category;
DROP TABLE IF EXISTS buyers;
CREATE TABLE buyer_category (
buyer_cat_id INT AUTO_INCREMENT,
category VARCHAR(15) NOT NULL,
description VARCHAR(500),
CONSTRAINT buyer_cat_pk
PRIMARY KEY (buyer_cat_id));
SELECT
#CASCADE actionCREATE TABLE buyers (
buyer_id INT AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
phone VARCHAR(15) NOT NULL UNIQUE,
address VARCHAR(255) NOT NULL,
rating TINYINT,
buyer_cat_id INT,
CONSTRAINT buysers_pk
PRIMARY KEY (buyer_id),
CONSTRAINT uc_name UNIQUE (name),
CONSTRAINT buyers_fk
FOREIGN KEY (buyer_cat_id)
REFERENCES buyer_category(buyer_cat_id)
ON UPDATE CASCADE
ON DELETE CASCADE);
SELECT
INSERT INTO buyer_category(category,description)
VALUES
('LT','Long Term Contract’),
('RT','Retail’),
('WS','Wholesale');
INSERT INTO buyers(name, phone, address, rating,
buyer_cat_id)
VALUES
('MFS', '244-2321-232', '45, Jess Road, TRNT', 9, 1),
('GGD', '543-2342-654', '5, Joal Road, KENS',5, 1),
('Mary Gold', '322-2121-543', '12, Hell Road, TRNT',4, 2),
('PBC', '232-1223-111', '45, Jurl Road, KENS',6, 3),
('KPM', '523-1245-633', '43, Jurl Road, KENS',7, 3),
('REES', '542-6422-543', '75, Hell Road, TRNT',2, 3);
Exercise 1
• Use test1.
• Add 2 more rows to buyers_category and 10
rows to buyers.
SELECT
#Selecting the data of one column from one table.
SELECT name FROM buyers;
#Selecting the data of two columns from one table.
SELECT name, phone FROM buyers;
#Selecting all columns from one table.
SELECT * FROM buyers;
#Selecting a value without the FROM part.
SELECT 10+10;
SELECT NOW();
SELECT CURRENT_DATE();
SELECT CONCAT('Lenny', ' ', 'Roggers');
Exercise 2
• Select the following data from the following
columns
Column / Data Table
1 description buyer_category
2 Your name -
3 Name
Phone
address
buyers
4 ALL buyer_category
5 ALL
Current Date
buyers
SELECT
SELECT select_list
FROM dual;
SELECT NOW() FROM dual;
• Sometimes, you still need to use the FROM clause but you
don’t want to reference any actual table. In this case, you can
use the dual table in the FROM clause.
SELECT expression AS column_alias;
SELECT expression column_alias;
SELECT select_list_with_aliases
FROM table_name;
SELECT NOW() FROM dual;
• Sometimes, you still need to use the FROM clause but you
don’t want to reference any actual table. In this case, you can
use the dual table in the FROM clause.
SELECT
SELECT expression AS column_alias;
SELECT expression column_alias;
SELECT select_list_with_aliases
FROM table_name;
SELECT NOW() AS current_date_time;
SELECT name AS buyer_name, phone AS buyer_phone
FROM buyers;
• To assign an alias to a column, you place the AS keyword
after the expression followed by a column alias.
• However, The AS keyword is with an expression optional.
MySQL Operators
MySQL
Operators and
Precedence
Operator Description
INTERVAL Date/Time Intervals
BINARY, COLLATE Binary Strings, Character Collation
! NOT
- (unary minus), ~ (unary bit inversion) Negation, bit inversion
^ *, /, DIV, %, MOD Product-related operators
-, + Summation-related operators
<<, >> Bitwise left shit, Bitwise right shift
& Bitwise AND
| Bitwise OR
= (comparison), <=>, >=, >, <=, <, <>, !=,
IS, LIKE, REGEXP, IN, MEMBER OF
Comparison Operators
BETWEEN, CASE, WHEN, THEN, ELSE Between clause, conditional selection
NOT NOT
AND, && AND
XOR XOR
OR, || OR
= (assignment), := Assignment
MySQL
Operators
Name Description
& Bitwise AND
> Greater than operator
>> Right shift
>= Greater than or equal operator
< Less than operator
<>, != Not equal operator
<< Left shift
<= Less than or equal operator
<=> NULL-safe equal to operator
%, MOD Modulo operator
* Multiplication operator
+ Addition operator
- Minus operator
- Change the sign of the argument
->
Return value from JSON column after evaluating path;
equivalent to JSON_EXTRACT().
->>
Return value from JSON column after evaluating path and
unquoting the result; equivalent to
JSON_UNQUOTE(JSON_EXTRACT()).
MySQL
Operators
Name Description
/ Division operator
:= Assign a value
=
Assign a value (as part of a SET statement, or as
part of the SET clause in an UPDATE statement)
= Equal operator
^ Bitwise XOR
AND, && Logical AND
BETWEEN ... AND ... Whether a value is within a range of values
BINARY Cast a string to a binary string
CASE Case operator
DIV Integer division
IN() Whether a value is within a set of values
IS Test a value against a boolean
IS NOT Test a value against a boolean
IS NOT NULL NOT NULL value test
IS NULL NULL value test
LIKE Simple pattern matching
MySQL
Operators
Name Description
MEMBER OF()
Returns true (1) if first operand matches any
element of JSON array passed as second operand,
otherwise returns false (0)
NOT, ! Negates value
NOT BETWEEN ...
AND ... Whether a value is not within a range of values
NOT IN() Whether a value is not within a set of values
NOT LIKE Negation of simple pattern matching
NOT REGEXP Negation of REGEXP
OR, || Logical OR
REGEXP Whether string matches regular expression
RLIKE Whether string matches regular expression
SOUNDS LIKE Compare sounds
XOR Logical XOR
| Bitwise OR
~ Bitwise inversion
SELECT Statement
with WHERE
(Filters/Subsetting)
SELECT and
WHERE
SELECT
select_list
FROM
table_name
WHERE
search_condition;
• search_condition: any combination of one or more expressions. You may
use logical operators such as, but not limited to, AND, OR and NOT.
• In MySQL, a predicate is a Boolean expression that evaluates to TRUE,
FALSE, or UNKNOWN. The output of a SELECT statement includes any row
that satisfies the search_condition.
• The WHERE clause is used also in the UPDATE or DELETE statement to
specify which rows to update or delete.
• When executing a SELECT statement with a WHERE clause, MySQL
evaluates the WHERE clause after the FROM clause and before the
SELECT and ORDER BY clauses.
MySQL
Logical and
Comparison
Operators
Name Description
AND, && Logical AND
NOT, ! Negates value
OR, || Logical OR
XOR Logical XOR
> Greater than operator
>= Greater than or equal operator
< Less than operator
<>, != Not equal operator
<= Less than or equal operator
<=> NULL-safe equal to operator
= Equal operator
SELECT and
WHERE
#Filter based on a numeric column.
SELECT name
FROM buyers
WHERE buyer_cat_id = 1;
#Filter based on a string/date column.
SELECT *
FROM buyers
WHERE name = 'GGD’;
SELECT name, phone
FROM buyers
WHERE name <> 'GGD';
Combining
Multiple
Logical
Expressions
with Logical
Operators
#AND
SELECT name, phone
FROM buyers
WHERE buyer_cat_id = 3 AND rating > 5;
SELECT name, phone
FROM buyers
WHERE buyer_cat_id = 3 && rating > 5;
#OR
SELECT name, phone
FROM buyers
WHERE name = 'GGD’ OR rating > 5;
SELECT name, phone
FROM buyers
WHERE name = 'GGD’ || rating > 5;
Combining
Multiple
Logical
Expressions
with Logical
Operators
#NOT
SELECT name, phone
FROM buyers
WHERE name = 'GGD' OR !rating > 5;
SELECT name, phone
FROM buyers
WHERE NOT(name = 'GGD' || rating > 5);
SELECT name, phone
FROM buyers
WHERE name != 'GGD';
Combining
Multiple
Logical
Expressions
with Logical
Operators
• The AND and OR operators are logical operators that
combine two or more Boolean expressions and returns 1, 0,
or NULL.
• In practice, you’ll use the AND, OR, and NOT operators in
the WHERE clause of the SELECT, UPDATE, DELETE
statements to form a condition. Also, you can use these
operators in the conditions of the JOIN clauses.
• Short-circuit evaluation: When evaluating an expression
that contains a logical operator, MySQL stops evaluating the
remaining parts of the expression as soon as it can
determine the result.
• MySQL evaluates the OR operator after the AND operator if
an expression contains both AND and OR operators.
Combining
Multiple Logical
Expressions with
Logical
Operators
AND Outcomes
TRUE FALSE NULL
TRUE TRUE FALSE NULL
FALSE FALSE FALSE FALSE
NULL NULL FALSE NULL
OR Outcomes
TRUE FALSE NULL
TRUE TRUE TRUE TRUE
FALSE TRUE FALSE NULL
NULL TRUE NULL NULL
<=> Operator
• NULL-safe equal. This operator performs an equality
comparison like the = operator, but returns 1 rather than
NULL if both operands are NULL, and 0 rather than NULL if
one operand is NULL.
• The <=> operator is equivalent to the standard SQL IS NOT
DISTINCT FROM operator.
SELECT 1 <=> 1, NULL <=> NULL, 1 <=> NULL;
SELECT 1 = 1, NULL = NULL, 1 = NULL;
Exercise 3
• Download customers.sql
(customermodels schema)
from Canvas and
understand the schema by
studying the given ERD
(database diagram):
Exercise 3
• use customermodels and extract the following
data:
1. All data of the customers in Las Vegas.
2. All data of the customers not in Las Vegas.
3. Name, phone, and address data of the customers
who have a credit limit greater than 10,000.
4. Order number and Order Date of all the on-hold
orders.
5. Name and phone of the customers neither in Las
Vegas nor Melbourne.
6. All data of the orders that were placed before 2005.
7. All the data of the orders that were placed in 2004.
8. Order number, shipped date, and comments of the
orders that were shipped in 2005.
9. Order number, shipped date, and comments of the
orders that were placed in 2004 and 2005 and had
any comment.
10. All the data of the orders that were not shipped, not
ordered in 2003, and with a comment.
11. All data of the employees who report to VP Sales.
SELECT Statement
with ORDER BY
SELECT
Statement
with ORDER
BY
SELECT select_list
FROM table_name
WHERE search_condition
ORDER BY
column1 [ASC|DESC],
column2 [ASC|DESC],
...;
USE test1;
SELECT * FROM buyers
WHERE rating > 5
ORDER BY rating DESC, name ASC;
• When querying data from a table, the order of rows in the
result set is unspecified. The ORDER BY clause is used to sort
the rows in the result set.
• The ASC stands for ascending and the DESC stands for
descending. ASC is optional, for it is the standard order.
SELECT
Statement
with ORDER
BY
USE test1;
SELECT name, phone, rating * 10 FROM buyers
WHERE rating > 5
ORDER BY rating * 10 DESC, name ASC;
SELECT name, phone, rating * 10 AS rating_percent FROM
buyers
WHERE rating > 5
ORDER BY rating_percent DESC, name ASC;
• Sometimes, your queries may include calculated
fields/columns. The full calculation must be included in
ORDER BY if the calculated column is used to sort the result
set.
• To make the query more readable, you can assign the
expression in the SELECT clause a column alias and use that
column alias in the ORDER BY clause.
Exercise 4
• use customermodels and extract the following
data:
1. All customer data ordered by customer ID.
2. All customer data sorted first by their last name
and then by first name, both in ascending order.
3. The full name and phone number of the
customers who are NOT based in Nantes, Las
Vegas, or Melbourne, sorted by name.
4. All data of the offices in Boston, NYC, Paris,
Tokyo, Sydney sorted by Country (Descending),
office (Ascending), and Postel Code (Ascedning).
5. Order Number, Order Line Number, Product
Code, Quantity Ordered, Unit Cost, and Total
Cost of Order Items with a unit cost greater than
50 and a quantity not less than 50 ordered,
sorted by Order Number, and Order Line
Number (both in ascending order).
SELECT Statement
with WHERE: Special
Cases
SELECT
Statement
with WHERE:
Special Cases
• SELECT DISTINCT - eliminate duplicate rows in a result set.
• BETWEEN –query data based on a range using BETWEEN
operator.
• IS NULL – test whether a value is NULL or not by using IS
NULL operator.
• IN – determine if a value matches any value in a set.
• LIKE – the technique to query data based on a simple text
pattern.
• LIMIT – use LIMIT to constrain the number of rows returned
by SELECT statement
SELECT
Statement
with WHERE:
SELECT
DISTINCT
SELECT DISTINCT select_list
FROM table_name
WHERE search_condition
USE test1;
SELECT DISTINCT rating FROM buyers;
• When querying data from a table, you may get duplicate rows. To remove
these duplicate rows, you use the DISTINCT clause in the SELECT
statement.
• you can specify one or more columns that you want to select distinct
values after the SELECT DISTINCT keywords. The DISTINCT clause will use
the values of these columns to evaluate the uniqueness of the rows.
• When you specify a column that has NULL values in the DISTINCT clause,
it will keep only one NULL value because it considers all NULL values are
the same.
SELECT
Statement
with WHERE:
BETWEEN
expression BETWEEN low AND high
USE test1;
SELECT * FROM buyers
WHERE rating BETWEEN 5 AND 8;
• The BETWEEN operator is a logical operator that specifies
whether a value is in a range or not.
• The BETWEEN operator returns 1 if: value >= low AND value
<= high. Otherwise, it returns 0.
• If the value, low, or high is NULL, the BETWEEN operator
returns NULL.
• To negate the BETWEEN operator, the NOT operator can be
used:
expression NOT BETWEEN low AND high
SELECT
Statement
with WHERE:
IS NULL
value IS NULL
value IS NOT NULL
USE test1;
INSERT INTO buyers(name, phone, address, rating, buyer_cat_id)
VALUES
('Gary Lake', ‘243-2221-276', ‘76, Kill Road, TRNT’, NULL, 2),
('HDDFE', '932-4321-233', ‘55, Roul Road, KENS’,NULL, 1)
SELECT * FROM buyers
WHERE rating IS NULL;
SELECT * FROM buyers
WHERE rating IS NOT NULL;
• To check if a value is NULL or not, the IS NULL operator is used, not the
equal operator (=). It returns TRUE if a value is NULL.
SELECT
Statement
with WHERE:
IS NULL
• If a DATE or DATETIME column has a NOT NULL constraint and contains a
special date '0000-00-00', you can use the IS NULL operator to find such
rows.
USE test1;
CREATE TABLE IF NOT EXISTS trip (
id INT AUTO_INCREMENT,
name VARCHAR(255),
destination VARCHAR(255),
begin_date DATE NOT NULL,
end_date DATE NOT NULL,
PRIMARY KEY(id)
);
INSERT INTO trip(name, destination. begin_date, end_date)
VALUES('Niagara', 'Niagara Falls', '2020-01-01','0000-00-00'),
('Blue Mountain', 'Blue Mountain', '2020-01-01','0000-00-00'),
('Museum', 'Museum Toronto', '2020-01-01','2030-01-01’);
SELECT * FROM trip
WHERE end_date IS NOT NULL;
SELECT
Statement
with WHERE:
IN
value IN (value1, value2, value3,...)
USE test1;
SELECT * FROM buyers
WHERE rating IN (5, 7, 9);
• The IN operator allows you to determine if a value matches
any value in a list of values.
• The IN operator returns 1 (true) if the value equals any value
in the list (value1, value2, value3,…). Otherwise, it returns 0.
• Generally, the IN operator returns NULL in two cases:
• The value on the left side of the operator is NULL.
• The value doesn’t equal any value in the list and one of
values in the list is NULL.
SELECT
Statement
with WHERE:
LIMIT
SELECT
select_list
FROM
table_name
ORDER BY
sort_expression
LIMIT offset, row_count;
USE test1;
SELECT * FROM buyers
ORDER BY name
LIMIT 3, 4;
• The LIMIT clause is used in the SELECT statement to constrain
the number of rows to return.
• The LIMIT clause accepts one or two arguments:
• The offset specifies the offset of the first row to return. The offset of
the first row is 0, not 1.
• The row_count specifies the maximum number of rows to return.
SELECT
Statement
with WHERE:
LIKE
expression LIKE pattern ESCAPE escape_character;
expression NOT LIKE pattern ESCAPE escape_character;
• The LIKE operator is a logical operator that tests whether a string
contains a specified pattern or not.
• If the expression matches the pattern, the LIKE operator returns 1.
Otherwise, it returns 0.
• MySQL provides two wildcard characters for constructing patterns:
• The percentage ( % ) wildcard: matches any string of zero or more
characters.
• The underscore ( _ ) wildcard: matches any single character.
• For example, k% matches any string starts with the character k such as
knife and kite. The ti_ matches any string starts with ti and is followed by
any character such as tip and tin.
• When the pattern contains the wildcard character and you want to treat
it as a regular character, you can use the ESCAPE clause. In this case, you
can use the ESCAPE clause to specify the escape character so that the
LIKE operator interprets the wildcard character as a literal character.
• If you don’t specify the escape character explicitly, the backslash
character () is the default escape character.
• For example, if you want to find products whose product codes contain
the string _20 , you can use the pattern %_20% with the default escape
character:
SELECT
Statement
with WHERE:
IS NULL
USE test1;
SELECT * FROM buyers
WHERE name LIKE g%;
SELECT * FROM buyers
WHERE name LIKE g__;
SELECT * FROM buyers
WHERE name NOT LIKE %g%;
Exercise 5
• use customermodels and extract the following
data:
1. Full name of the employees who work for the offices
1,4, and 5.
2. All data of the customers who the second highest
and third highest credit limit.
3. All data of the customers whose name starts with ‘a’.
4. Order Numbers of order that had at least one item
with a total cost greater than $ 200.
5. All data of the employees whose last name starts
with ‘p’ and who work for the office 1.
6. All data of the employees with E and S in any part of
their name.
7. Order Number, Order Line Number, Product Code,
and Total Cost of Order Items with a unit cost
between 50 and 100 and a total cost that is less than
1000, sorted by Order Number, and Order Line
Number (both in ascending order).
8. Name and phone of the customers who are in
France, USA, Australia, or Norway whose Address
Line 2 is Not Null.

More Related Content

Similar to SQL Lesson 6 - Select.pdf

Similar to SQL Lesson 6 - Select.pdf (20)

Query
QueryQuery
Query
 
Oracle: Basic SQL
Oracle: Basic SQLOracle: Basic SQL
Oracle: Basic SQL
 
Oracle: Basic SQL
Oracle: Basic SQLOracle: Basic SQL
Oracle: Basic SQL
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL- Introduction to MySQL
SQL- Introduction to MySQLSQL- Introduction to MySQL
SQL- Introduction to MySQL
 
Basic SQL Statments
Basic SQL StatmentsBasic SQL Statments
Basic SQL Statments
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
MySQL basics
MySQL basicsMySQL basics
MySQL basics
 
Les06
Les06Les06
Les06
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptx
 
Data Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdfData Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdf
 
ADV Powepoint 2 Lec.pptx
ADV Powepoint 2 Lec.pptxADV Powepoint 2 Lec.pptx
ADV Powepoint 2 Lec.pptx
 
Les02
Les02Les02
Les02
 
Sql
SqlSql
Sql
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
Restricting and sorting data
Restricting and sorting dataRestricting and sorting data
Restricting and sorting data
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
 
Module03
Module03Module03
Module03
 
ALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMSALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMS
 

More from Madhusha15

Chapter 3A (2).pptx
Chapter 3A (2).pptxChapter 3A (2).pptx
Chapter 3A (2).pptxMadhusha15
 
Chapter 1A.pptx
Chapter 1A.pptxChapter 1A.pptx
Chapter 1A.pptxMadhusha15
 
Class 8 -Authentication Controls.pptx
Class 8 -Authentication Controls.pptxClass 8 -Authentication Controls.pptx
Class 8 -Authentication Controls.pptxMadhusha15
 
Class 7- XIoT and Botnets.pptx
Class 7- XIoT and Botnets.pptxClass 7- XIoT and Botnets.pptx
Class 7- XIoT and Botnets.pptxMadhusha15
 
Day 7 Project Cost Management .pdf
Day 7 Project Cost Management .pdfDay 7 Project Cost Management .pdf
Day 7 Project Cost Management .pdfMadhusha15
 
Management and Team Building.pptx
Management and Team Building.pptxManagement and Team Building.pptx
Management and Team Building.pptxMadhusha15
 
time mamangement.ppt
time mamangement.ppttime mamangement.ppt
time mamangement.pptMadhusha15
 

More from Madhusha15 (7)

Chapter 3A (2).pptx
Chapter 3A (2).pptxChapter 3A (2).pptx
Chapter 3A (2).pptx
 
Chapter 1A.pptx
Chapter 1A.pptxChapter 1A.pptx
Chapter 1A.pptx
 
Class 8 -Authentication Controls.pptx
Class 8 -Authentication Controls.pptxClass 8 -Authentication Controls.pptx
Class 8 -Authentication Controls.pptx
 
Class 7- XIoT and Botnets.pptx
Class 7- XIoT and Botnets.pptxClass 7- XIoT and Botnets.pptx
Class 7- XIoT and Botnets.pptx
 
Day 7 Project Cost Management .pdf
Day 7 Project Cost Management .pdfDay 7 Project Cost Management .pdf
Day 7 Project Cost Management .pdf
 
Management and Team Building.pptx
Management and Team Building.pptxManagement and Team Building.pptx
Management and Team Building.pptx
 
time mamangement.ppt
time mamangement.ppttime mamangement.ppt
time mamangement.ppt
 

Recently uploaded

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 

Recently uploaded (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 

SQL Lesson 6 - Select.pdf

  • 1.
  • 2. Data Handling & Decision Making Madhusha (Maddy) Nanayakkara
  • 3. SQL & MYSQL FOR DATA ANALYTICS SERIES Lesson 6 Data Manipulation with SQL: SELECT, WHERE, ORDER BY
  • 5. SELECT SELECT select_list FROM table_name; • select_list: specify one or more columns from which you want to select data after the SELECT keyword. If the select_list has multiple columns, you need to separate them by a comma (,). • table_name: specify the name of the table from which you want to select data after the FROM keyword.
  • 6. SELECT CREATE DATABASE IF NOT EXISTS test1; USE test1; ALTER TABLE buyersDROP FOREIGN KEY buyers_fk; DROP TABLE IF EXISTS buyer_category; DROP TABLE IF EXISTS buyers; CREATE TABLE buyer_category ( buyer_cat_id INT AUTO_INCREMENT, category VARCHAR(15) NOT NULL, description VARCHAR(500), CONSTRAINT buyer_cat_pk PRIMARY KEY (buyer_cat_id));
  • 7. SELECT #CASCADE actionCREATE TABLE buyers ( buyer_id INT AUTO_INCREMENT, name VARCHAR(255) NOT NULL, phone VARCHAR(15) NOT NULL UNIQUE, address VARCHAR(255) NOT NULL, rating TINYINT, buyer_cat_id INT, CONSTRAINT buysers_pk PRIMARY KEY (buyer_id), CONSTRAINT uc_name UNIQUE (name), CONSTRAINT buyers_fk FOREIGN KEY (buyer_cat_id) REFERENCES buyer_category(buyer_cat_id) ON UPDATE CASCADE ON DELETE CASCADE);
  • 8. SELECT INSERT INTO buyer_category(category,description) VALUES ('LT','Long Term Contract’), ('RT','Retail’), ('WS','Wholesale'); INSERT INTO buyers(name, phone, address, rating, buyer_cat_id) VALUES ('MFS', '244-2321-232', '45, Jess Road, TRNT', 9, 1), ('GGD', '543-2342-654', '5, Joal Road, KENS',5, 1), ('Mary Gold', '322-2121-543', '12, Hell Road, TRNT',4, 2), ('PBC', '232-1223-111', '45, Jurl Road, KENS',6, 3), ('KPM', '523-1245-633', '43, Jurl Road, KENS',7, 3), ('REES', '542-6422-543', '75, Hell Road, TRNT',2, 3);
  • 9. Exercise 1 • Use test1. • Add 2 more rows to buyers_category and 10 rows to buyers.
  • 10. SELECT #Selecting the data of one column from one table. SELECT name FROM buyers; #Selecting the data of two columns from one table. SELECT name, phone FROM buyers; #Selecting all columns from one table. SELECT * FROM buyers; #Selecting a value without the FROM part. SELECT 10+10; SELECT NOW(); SELECT CURRENT_DATE(); SELECT CONCAT('Lenny', ' ', 'Roggers');
  • 11. Exercise 2 • Select the following data from the following columns Column / Data Table 1 description buyer_category 2 Your name - 3 Name Phone address buyers 4 ALL buyer_category 5 ALL Current Date buyers
  • 12. SELECT SELECT select_list FROM dual; SELECT NOW() FROM dual; • Sometimes, you still need to use the FROM clause but you don’t want to reference any actual table. In this case, you can use the dual table in the FROM clause. SELECT expression AS column_alias; SELECT expression column_alias; SELECT select_list_with_aliases FROM table_name; SELECT NOW() FROM dual; • Sometimes, you still need to use the FROM clause but you don’t want to reference any actual table. In this case, you can use the dual table in the FROM clause.
  • 13. SELECT SELECT expression AS column_alias; SELECT expression column_alias; SELECT select_list_with_aliases FROM table_name; SELECT NOW() AS current_date_time; SELECT name AS buyer_name, phone AS buyer_phone FROM buyers; • To assign an alias to a column, you place the AS keyword after the expression followed by a column alias. • However, The AS keyword is with an expression optional.
  • 15. MySQL Operators and Precedence Operator Description INTERVAL Date/Time Intervals BINARY, COLLATE Binary Strings, Character Collation ! NOT - (unary minus), ~ (unary bit inversion) Negation, bit inversion ^ *, /, DIV, %, MOD Product-related operators -, + Summation-related operators <<, >> Bitwise left shit, Bitwise right shift & Bitwise AND | Bitwise OR = (comparison), <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN, MEMBER OF Comparison Operators BETWEEN, CASE, WHEN, THEN, ELSE Between clause, conditional selection NOT NOT AND, && AND XOR XOR OR, || OR = (assignment), := Assignment
  • 16. MySQL Operators Name Description & Bitwise AND > Greater than operator >> Right shift >= Greater than or equal operator < Less than operator <>, != Not equal operator << Left shift <= Less than or equal operator <=> NULL-safe equal to operator %, MOD Modulo operator * Multiplication operator + Addition operator - Minus operator - Change the sign of the argument -> Return value from JSON column after evaluating path; equivalent to JSON_EXTRACT(). ->> Return value from JSON column after evaluating path and unquoting the result; equivalent to JSON_UNQUOTE(JSON_EXTRACT()).
  • 17. MySQL Operators Name Description / Division operator := Assign a value = Assign a value (as part of a SET statement, or as part of the SET clause in an UPDATE statement) = Equal operator ^ Bitwise XOR AND, && Logical AND BETWEEN ... AND ... Whether a value is within a range of values BINARY Cast a string to a binary string CASE Case operator DIV Integer division IN() Whether a value is within a set of values IS Test a value against a boolean IS NOT Test a value against a boolean IS NOT NULL NOT NULL value test IS NULL NULL value test LIKE Simple pattern matching
  • 18. MySQL Operators Name Description MEMBER OF() Returns true (1) if first operand matches any element of JSON array passed as second operand, otherwise returns false (0) NOT, ! Negates value NOT BETWEEN ... AND ... Whether a value is not within a range of values NOT IN() Whether a value is not within a set of values NOT LIKE Negation of simple pattern matching NOT REGEXP Negation of REGEXP OR, || Logical OR REGEXP Whether string matches regular expression RLIKE Whether string matches regular expression SOUNDS LIKE Compare sounds XOR Logical XOR | Bitwise OR ~ Bitwise inversion
  • 20. SELECT and WHERE SELECT select_list FROM table_name WHERE search_condition; • search_condition: any combination of one or more expressions. You may use logical operators such as, but not limited to, AND, OR and NOT. • In MySQL, a predicate is a Boolean expression that evaluates to TRUE, FALSE, or UNKNOWN. The output of a SELECT statement includes any row that satisfies the search_condition. • The WHERE clause is used also in the UPDATE or DELETE statement to specify which rows to update or delete. • When executing a SELECT statement with a WHERE clause, MySQL evaluates the WHERE clause after the FROM clause and before the SELECT and ORDER BY clauses.
  • 21. MySQL Logical and Comparison Operators Name Description AND, && Logical AND NOT, ! Negates value OR, || Logical OR XOR Logical XOR > Greater than operator >= Greater than or equal operator < Less than operator <>, != Not equal operator <= Less than or equal operator <=> NULL-safe equal to operator = Equal operator
  • 22. SELECT and WHERE #Filter based on a numeric column. SELECT name FROM buyers WHERE buyer_cat_id = 1; #Filter based on a string/date column. SELECT * FROM buyers WHERE name = 'GGD’; SELECT name, phone FROM buyers WHERE name <> 'GGD';
  • 23. Combining Multiple Logical Expressions with Logical Operators #AND SELECT name, phone FROM buyers WHERE buyer_cat_id = 3 AND rating > 5; SELECT name, phone FROM buyers WHERE buyer_cat_id = 3 && rating > 5; #OR SELECT name, phone FROM buyers WHERE name = 'GGD’ OR rating > 5; SELECT name, phone FROM buyers WHERE name = 'GGD’ || rating > 5;
  • 24. Combining Multiple Logical Expressions with Logical Operators #NOT SELECT name, phone FROM buyers WHERE name = 'GGD' OR !rating > 5; SELECT name, phone FROM buyers WHERE NOT(name = 'GGD' || rating > 5); SELECT name, phone FROM buyers WHERE name != 'GGD';
  • 25. Combining Multiple Logical Expressions with Logical Operators • The AND and OR operators are logical operators that combine two or more Boolean expressions and returns 1, 0, or NULL. • In practice, you’ll use the AND, OR, and NOT operators in the WHERE clause of the SELECT, UPDATE, DELETE statements to form a condition. Also, you can use these operators in the conditions of the JOIN clauses. • Short-circuit evaluation: When evaluating an expression that contains a logical operator, MySQL stops evaluating the remaining parts of the expression as soon as it can determine the result. • MySQL evaluates the OR operator after the AND operator if an expression contains both AND and OR operators.
  • 26. Combining Multiple Logical Expressions with Logical Operators AND Outcomes TRUE FALSE NULL TRUE TRUE FALSE NULL FALSE FALSE FALSE FALSE NULL NULL FALSE NULL OR Outcomes TRUE FALSE NULL TRUE TRUE TRUE TRUE FALSE TRUE FALSE NULL NULL TRUE NULL NULL
  • 27. <=> Operator • NULL-safe equal. This operator performs an equality comparison like the = operator, but returns 1 rather than NULL if both operands are NULL, and 0 rather than NULL if one operand is NULL. • The <=> operator is equivalent to the standard SQL IS NOT DISTINCT FROM operator. SELECT 1 <=> 1, NULL <=> NULL, 1 <=> NULL; SELECT 1 = 1, NULL = NULL, 1 = NULL;
  • 28. Exercise 3 • Download customers.sql (customermodels schema) from Canvas and understand the schema by studying the given ERD (database diagram):
  • 29. Exercise 3 • use customermodels and extract the following data: 1. All data of the customers in Las Vegas. 2. All data of the customers not in Las Vegas. 3. Name, phone, and address data of the customers who have a credit limit greater than 10,000. 4. Order number and Order Date of all the on-hold orders. 5. Name and phone of the customers neither in Las Vegas nor Melbourne. 6. All data of the orders that were placed before 2005. 7. All the data of the orders that were placed in 2004. 8. Order number, shipped date, and comments of the orders that were shipped in 2005. 9. Order number, shipped date, and comments of the orders that were placed in 2004 and 2005 and had any comment. 10. All the data of the orders that were not shipped, not ordered in 2003, and with a comment. 11. All data of the employees who report to VP Sales.
  • 31. SELECT Statement with ORDER BY SELECT select_list FROM table_name WHERE search_condition ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...; USE test1; SELECT * FROM buyers WHERE rating > 5 ORDER BY rating DESC, name ASC; • When querying data from a table, the order of rows in the result set is unspecified. The ORDER BY clause is used to sort the rows in the result set. • The ASC stands for ascending and the DESC stands for descending. ASC is optional, for it is the standard order.
  • 32. SELECT Statement with ORDER BY USE test1; SELECT name, phone, rating * 10 FROM buyers WHERE rating > 5 ORDER BY rating * 10 DESC, name ASC; SELECT name, phone, rating * 10 AS rating_percent FROM buyers WHERE rating > 5 ORDER BY rating_percent DESC, name ASC; • Sometimes, your queries may include calculated fields/columns. The full calculation must be included in ORDER BY if the calculated column is used to sort the result set. • To make the query more readable, you can assign the expression in the SELECT clause a column alias and use that column alias in the ORDER BY clause.
  • 33. Exercise 4 • use customermodels and extract the following data: 1. All customer data ordered by customer ID. 2. All customer data sorted first by their last name and then by first name, both in ascending order. 3. The full name and phone number of the customers who are NOT based in Nantes, Las Vegas, or Melbourne, sorted by name. 4. All data of the offices in Boston, NYC, Paris, Tokyo, Sydney sorted by Country (Descending), office (Ascending), and Postel Code (Ascedning). 5. Order Number, Order Line Number, Product Code, Quantity Ordered, Unit Cost, and Total Cost of Order Items with a unit cost greater than 50 and a quantity not less than 50 ordered, sorted by Order Number, and Order Line Number (both in ascending order).
  • 35. SELECT Statement with WHERE: Special Cases • SELECT DISTINCT - eliminate duplicate rows in a result set. • BETWEEN –query data based on a range using BETWEEN operator. • IS NULL – test whether a value is NULL or not by using IS NULL operator. • IN – determine if a value matches any value in a set. • LIKE – the technique to query data based on a simple text pattern. • LIMIT – use LIMIT to constrain the number of rows returned by SELECT statement
  • 36. SELECT Statement with WHERE: SELECT DISTINCT SELECT DISTINCT select_list FROM table_name WHERE search_condition USE test1; SELECT DISTINCT rating FROM buyers; • When querying data from a table, you may get duplicate rows. To remove these duplicate rows, you use the DISTINCT clause in the SELECT statement. • you can specify one or more columns that you want to select distinct values after the SELECT DISTINCT keywords. The DISTINCT clause will use the values of these columns to evaluate the uniqueness of the rows. • When you specify a column that has NULL values in the DISTINCT clause, it will keep only one NULL value because it considers all NULL values are the same.
  • 37. SELECT Statement with WHERE: BETWEEN expression BETWEEN low AND high USE test1; SELECT * FROM buyers WHERE rating BETWEEN 5 AND 8; • The BETWEEN operator is a logical operator that specifies whether a value is in a range or not. • The BETWEEN operator returns 1 if: value >= low AND value <= high. Otherwise, it returns 0. • If the value, low, or high is NULL, the BETWEEN operator returns NULL. • To negate the BETWEEN operator, the NOT operator can be used: expression NOT BETWEEN low AND high
  • 38. SELECT Statement with WHERE: IS NULL value IS NULL value IS NOT NULL USE test1; INSERT INTO buyers(name, phone, address, rating, buyer_cat_id) VALUES ('Gary Lake', ‘243-2221-276', ‘76, Kill Road, TRNT’, NULL, 2), ('HDDFE', '932-4321-233', ‘55, Roul Road, KENS’,NULL, 1) SELECT * FROM buyers WHERE rating IS NULL; SELECT * FROM buyers WHERE rating IS NOT NULL; • To check if a value is NULL or not, the IS NULL operator is used, not the equal operator (=). It returns TRUE if a value is NULL.
  • 39. SELECT Statement with WHERE: IS NULL • If a DATE or DATETIME column has a NOT NULL constraint and contains a special date '0000-00-00', you can use the IS NULL operator to find such rows. USE test1; CREATE TABLE IF NOT EXISTS trip ( id INT AUTO_INCREMENT, name VARCHAR(255), destination VARCHAR(255), begin_date DATE NOT NULL, end_date DATE NOT NULL, PRIMARY KEY(id) ); INSERT INTO trip(name, destination. begin_date, end_date) VALUES('Niagara', 'Niagara Falls', '2020-01-01','0000-00-00'), ('Blue Mountain', 'Blue Mountain', '2020-01-01','0000-00-00'), ('Museum', 'Museum Toronto', '2020-01-01','2030-01-01’); SELECT * FROM trip WHERE end_date IS NOT NULL;
  • 40. SELECT Statement with WHERE: IN value IN (value1, value2, value3,...) USE test1; SELECT * FROM buyers WHERE rating IN (5, 7, 9); • The IN operator allows you to determine if a value matches any value in a list of values. • The IN operator returns 1 (true) if the value equals any value in the list (value1, value2, value3,…). Otherwise, it returns 0. • Generally, the IN operator returns NULL in two cases: • The value on the left side of the operator is NULL. • The value doesn’t equal any value in the list and one of values in the list is NULL.
  • 41. SELECT Statement with WHERE: LIMIT SELECT select_list FROM table_name ORDER BY sort_expression LIMIT offset, row_count; USE test1; SELECT * FROM buyers ORDER BY name LIMIT 3, 4; • The LIMIT clause is used in the SELECT statement to constrain the number of rows to return. • The LIMIT clause accepts one or two arguments: • The offset specifies the offset of the first row to return. The offset of the first row is 0, not 1. • The row_count specifies the maximum number of rows to return.
  • 42. SELECT Statement with WHERE: LIKE expression LIKE pattern ESCAPE escape_character; expression NOT LIKE pattern ESCAPE escape_character; • The LIKE operator is a logical operator that tests whether a string contains a specified pattern or not. • If the expression matches the pattern, the LIKE operator returns 1. Otherwise, it returns 0. • MySQL provides two wildcard characters for constructing patterns: • The percentage ( % ) wildcard: matches any string of zero or more characters. • The underscore ( _ ) wildcard: matches any single character. • For example, k% matches any string starts with the character k such as knife and kite. The ti_ matches any string starts with ti and is followed by any character such as tip and tin. • When the pattern contains the wildcard character and you want to treat it as a regular character, you can use the ESCAPE clause. In this case, you can use the ESCAPE clause to specify the escape character so that the LIKE operator interprets the wildcard character as a literal character. • If you don’t specify the escape character explicitly, the backslash character () is the default escape character. • For example, if you want to find products whose product codes contain the string _20 , you can use the pattern %_20% with the default escape character:
  • 43. SELECT Statement with WHERE: IS NULL USE test1; SELECT * FROM buyers WHERE name LIKE g%; SELECT * FROM buyers WHERE name LIKE g__; SELECT * FROM buyers WHERE name NOT LIKE %g%;
  • 44. Exercise 5 • use customermodels and extract the following data: 1. Full name of the employees who work for the offices 1,4, and 5. 2. All data of the customers who the second highest and third highest credit limit. 3. All data of the customers whose name starts with ‘a’. 4. Order Numbers of order that had at least one item with a total cost greater than $ 200. 5. All data of the employees whose last name starts with ‘p’ and who work for the office 1. 6. All data of the employees with E and S in any part of their name. 7. Order Number, Order Line Number, Product Code, and Total Cost of Order Items with a unit cost between 50 and 100 and a total cost that is less than 1000, sorted by Order Number, and Order Line Number (both in ascending order). 8. Name and phone of the customers who are in France, USA, Australia, or Norway whose Address Line 2 is Not Null.