0% found this document useful (0 votes)
9 views

Is222 - Concat

SQL

Uploaded by

Stay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Is222 - Concat

SQL

Uploaded by

Stay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Intro to SQL Cont’d

Concatenation – In More detail

• You can find a list of string related functions


at this link:
– http://dev.mysql.com/doc/refman/5.1/en/stri
ng-functions.html
• concat and concat_ws are are two key
functions that we will use
• Both the functions deal with the concatenation
of strings
• What is the difference between the two?
2

1
Concatenation
• CONCAT() returns NULL if any argument is
NULL. The example shows the concatenation
of string literals.

Concatenation
• CONCAT_WS() stands for Concatenate With Separator
and is a special form of CONCAT().
• The first argument is the separator for the rest of the
arguments.
• The separator can be anything like a space, for
instance
• The separator is added between the strings to be
concatenated.
• The separator can be a string, as can the rest of the
arguments.
• If the separator is NULL, the result is NULL.
4

2
Concatenation
• CONCAT_WS() does not skip empty strings.
• However, it does skip any NULL values after the
separator argument.

• For the above, what is the result with concat?


• So which function should you use?
– You can use either.
– However, concat_ws is more useful when you deal
with null values 5

Concat Example - How can I combine the first


name and last name?

• Use the CONCAT function in MySQL (look at the


column names in the output).
• What will be the solution with concat_ws?

• MS Access

• SELECT cus_code, cus_fname & " " &


cus_lname FROM CUSTOMER; 6

3
Concat Example - How can I combine the first
name and last name?
• What happens if you use the & or + operator
instead of the concatenate functions in MySql?
• For instance, what would be the result of the
following query in MySql?
– SELECT cus_code, cus_fname & " " &
cus_lname FROM CUSTOMER;
– SELECT cus_code, cus_fname + " " +
cus_lname FROM CUSTOMER;

• Try out these queries in your own time and note


the results. 7

Aliases (As)
• An alias can be used in a query select list, to
give a column a different name.
• Use the AS operator to create an alias
• You can use the alias in GROUP BY, ORDER
BY, or HAVING clauses to refer to the column:

4
Aliases (as)
• Standard SQL disallows references to column aliases in a
WHERE clause.
• This restriction is imposed because when the WHERE
clause is evaluated, the column value may not yet have
been determined.
• For example, the following query is illegal:

• The WHERE clause determines which rows should be


included in the GROUP BY clause,
– but it refers to the alias of a column value that is not known until
after the rows have been selected, and grouped by the GROUP
BY.
9

Aliases (as)
• In the select list of a query, a quoted column alias can be
specified using identifier or string quoting characters
– SELECT 1 AS `one`, 2 AS 'two';
• Elsewhere in the statement, quoted references to the alias
must use identifier quoting, or the reference is treated as a
string literal.
• For example, this statement groups by the values in column
id, referenced using the alias `a`:
– SELECT id AS 'a', COUNT(*) AS cnt FROM tbl_name
GROUP BY `a`;
• But this statement groups by the literal string 'a' and will not
work as expected:
– SELECT id AS 'a', COUNT(*) AS cnt FROM tbl_name
GROUP BY 'a';
10

5
Aliases example
• https://dev.mysql.com/doc/refman/5.1/en/problems-with-
alias.html (MySql 5.1 reference for As)
• The example below gives the full name generated with concat
using an alias called Name

11

Aliases Exercise 1
• Consider the following columns in a customer table:

• Write a query to show all the details of all the customers from the table
above
• Consider the customer code to be a number
• cus_code should be aliased as Customer Code (two words).
• The first and last names should be concatenated such that they are not
nullified by null entries of the first/last name with the alias FullName.
• Spend about 1-2 minutes on this (answer is on the next slide)
12
• How many solutions are possible?

6
Aliases Exercise 1 - Solution
• Consider the following columns in a customer table:

• select cus_code as 'Customer Code', concat_ws(' ', cus_fname,


cus_lname) as FullName from customer;
– OR
• select cus_code as `Customer Code`, concat_ws(' ', cus_fname,
cus_lname) as FullName from customer;
13
• Note the difference in the solutions.

Arithmetic Operators
• A list of arithmetic operators are given below

• If any of the operands of a +, -, /, *, % is a real or string value, the precision of


the result is the precision of the operand with the maximum precision.
• In division performed with /, the scale of the result when using two exact-value
operands is the scale of the first operand plus the value of the
div_precision_increment system variable (which is 4 by default).
• For example, the result of the expression 5.05 / 0.014 has a scale of six decimal
places (360.714286)
• https://dev.mysql.com/doc/refman/5.1/en/arithmetic-functions.html (see the link for
full details)
14

7
Using Calculations - Example
• Consider the line table below

• List the invoice number, product code, and the total value of sales of that
product (line qty * line price) - Use arithmetic operators 15

Using Calculations - Example


• List the invoice number, product code, and the
total value of sales of that product (line qty *
line price). The product is the line_total

16

8
IFNULL
• Control Flow Functions

• Sometimes we need to control the flow of statements and the result


that is returned based on some condition

• For instance, if a particular value is null, we may wish to return some


expression instead of a null value.

• We consider one such function as follows:

• IFNULL(expr1,expr2)

– Expr1 is expression 1 and expr2 is expression 2

– If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2.

– IFNULL() returns a numeric or string value, depending on the context in


which it is used.

17

IFNULL
• Some examples can be seen as follows:

• The default result value of IFNULL(expr1,expr2) is the more “general” of the


two expressions, in the order STRING, REAL, or INTEGER.

• Consider the case of a table based on expressions or where MySQL must


internally store a value returned by IFNULL() in a temporary table:

• There will be a data row with the test field having the value 1
18

9
Special Operators
• A list of different operators is given at the link below:
– https://dev.mysql.com/doc/refman/5.1/en/non-typed-
operators.html

• Some key operators of significance


• BETWEEN

• LIKE

• IS NOT NULL

• IS NULL

• IS NOT

• IS
19
• NOT

Special Operators - Between


• The BETWEEN operator selects values within a range.
• The values can be numbers, text, or dates.
• You can use BETWEEN clause to replace a combination of "greater than equal
AND less than equal" conditions.
• See the example below and the output results
• Between:
– Select the customer codes and names for those customers whose
balance is between 200 and 400

20

10
Special Operators – IS NULL

• IS NULL
– Checks whether a particular column is null.
• Example: select all customers who do not have
a middle name

21

Special Operators - LIKE


• Like
– used when we want to match a particular pattern
– Pattern matching is done using SQL simple regular expression
comparison.
– Returns 1 (TRUE) or 0 (FALSE).
– The pattern need not be a literal string.

• For example, it can be specified as a string expression or table


column.
• This is used when we don’t have a particular value to compare with
but we have an idea of the value.
• The full reference is given here
• https://dev.mysql.com/doc/refman/5.1/en/string-comparison-
functions.html#operator_like
22

11
Special Operators - LIKE
• With LIKE you can use the following two wildcard characters in the
pattern.

• To test for literal instances of a wildcard character, precede it by the


escape character.
• If you do not specify the ESCAPE character, “\” is assumed.

23

Special Operators - LIKE


• Like
– Example: List the customers whose last name
starts with the letter ‘O’
– Note the use of % - this means any value of
any length can come after ‘O’

24

12
Special Operators - LIKE
• Like
– like ‘_m%’ means that the second letter
of the last name should be ‘m’ followed
by anything else

25

Special Operators - LIKE


• Like
– Like is a very useful operator overall
– For instance, if we need to search for the title
of a particular book in a database, we may not
wish to type the whole title but part of it in
the search
– Similarly, if we searched by the author name,
we might just wish to get a set of results after
writing only part of the author’s name
– Think about how searches in Google happen.
– You only type part of the search and Google
yields invaluable results
– Think about other situations where you could
use LIKE in your queries 26

13
Special Operators - IN
• expr IN (value list)

• Returns 1 if expr (expression) is equal to any of the


values in the IN list, else returns 0.
• IN is very quick if the IN value list consists entirely of
constants.
• This is an important operator when you want to get all
the rows in a table whose column value is in some
known list
• For instance, finding all customers in a list of cities.
– You can check if the customer city is in one from a given
list of cities, instead of checking as a combination of 27
expressions

Special Operators - IN

• IN
– Allows you to specify a list of values
– Consider the invoice table

28

14
Special Operators - IN

• Select the invoice numbers of those invoices


that were made for the customer with cus_code
10018, 10012, 10014

29

Joining Database Tables


• How can you retrieve data from • The following tables show the
multiple tables? relationship between Product
• Tables should be related and Vendor
• You should know the PK and FK • What is the foreign key?
• You can put the join condition in
the WHERE clause
• There are different kinds of
joins, each with a different
purpose
• Think about a query where you
have to find the number of
products by a particular vendor.
• You need to locate the vendor
from the vendor table and find
matches of products with the
same vendor to get a count 30

15
Joining Database Tables
• The product table has the v_code only
• How can you list the product and the name of the
vendor?
• The name of the vendor is the vendor table
• You need to join the two tables together
• You will do this using the foreign key in the table
design
• You will need a join query to combine the info
from both tables

• The full reference for joins is located at:


– https://dev.mysql.com/doc/refman/5.1/en/jo
in.html
31

Joining Database Tables


• One of the ways of joining tables is to make
selections of attributes from the respective tables
and use a where clause to filter the required rows
• Other ways joining info from different tables is to
use clauses such as INNER JOIN, LEFT JOIN, RIGHT
JOIN
• The above clauses can be convenient, but
sometimes difficult to write
• Another possibility is to use sub queries (a query
within a query)
• Be sure to see the full MySql 5.1 join reference
32

16
Joining Database Tables

• So how can we join info from different tables?


• We first have to understand what happens if we just
join 2 tables without any filter restrictions
• If you write a query such as
– select table1.a1, table2.b1 from table1, table2;
• You will get a cartesian product which will pair up every
value of a1 with every value of b1 from the second table
• Let’s just consider an example on the next slide with the
following tables:
– Student
– Guardian

33

Joining Database Tables

• The student and guardian tables are follows (student on the left):

• If we write the query (w/o any filter clause), the results will be:
– select student.stu_id, guardian.guard_id from student, guardian order
by student.stu_id;

34

17
Joining Database Tables

• Now, if we write the query (with some filter clause), the results will
be:
– select student.stu_id, guardian.guard_id from student, guardian where
student.stu_id = "S1" order by student.stu_id ;

• All the rows were filtered to only include records for S1, but still
creating all permutations of S1 with every row in the guardian table

35

Joining Database Tables - Example

• Let’s look at this example


• List the p_code, p_descript, v_code, v_name for all
products.
• So how can we do this?
• Essentially include each attribute in the query and
specify the tables from which the selections are being
made (prouct and vendor)
• Then you can use a filter clause with where

36

18
Joining Database Tables

37

Joining Database Tables

• product.v_code = vendor.v_code;

• This statement creates a natural join between


product and vendor tables

• The statement only picks the those rows where


the v_code value in the product table matches
the v_code value of the vendor table

38

19
Joining Database Tables – Exercise 1

• Exercise:

• List the p_code, p_descript, v_code,


v_name for all products that is supplied by
vendor with v_code = 21344.

• Spend about 1 minute on this question


(solution on the next slide)

39

Joining Database Tables – Exercise 1

• List the p_code, p_descript, v_code, v_name


for all products that is supplied by vendor with
v_code = 21344.
• Solution

40

20
Joining Database Tables – Exercise 2

• Write the condition that joins the customer


and invoice table. Spend about a minute on
this (work this out yourself)

41

References

• https://dev.mysql.com/doc/refman/5.1/en/contro
l-flow-functions.html#function_ifnull
• http://www.tutorialspoint.com/mysql/mysql-
between-clause.htm
• https://dev.mysql.com/doc/refman/5.0/en/string-
comparison-functions.html#operator_like
• https://dev.mysql.com/doc/refman/5.1/en/comp
arison-operators.html#function_in

42

21

You might also like