CS122 Using Relational Databases and SQL 12/7/2018 CS122 Using Relational Databases and SQL 6. Functions Daniel Firpo Slides prepared by Randy Moss Department of Computer Science California State University, Los Angeles
Objectives Concatenate text fields Text and data manipulation 12/7/2018 Objectives Concatenate text fields Text and data manipulation Date manipulation Manipulate null values Data type conversion Misc functions 6. Functions CS1222_F2018
12/7/2018 Concatenation Concatenation is the combination of two or more text values into one text value Can concatenate multiple fields or fields with constant text 6. Functions CS1222_F2018
Concatenation Syntax Concat(expression1, expression2,…) 12/7/2018 Concatenation Syntax Concat(expression1, expression2,…) Concatenate a series of text values separated by commas If any of the arguments is null, the function will return null Concat_WS(Separator, expression1, expression2,…) The separator is placed between each of the text values The function will ignore nulls unless the separator is a null, in which case it returns a null. 6. Functions CS1222_F2018
Concatenation Example (1) 12/7/2018 Concatenation Example (1) List the full name of each member Select Concat_WS(' ', firstname , lastname) As fullname From Members 6. Functions CS1222_F2018
Concatenation Example (2) 12/7/2018 Concatenation Example (2) Report the City, State, and Zip of each member, formatted as City, State Zip. SELECT Concat(City, ' ' ,Region,' ', Postalcode) As MailAddr FROM Members 6. Functions CS1222_F2018
Concatenation Example (3) 12/7/2018 Concatenation Example (3) Report each lead source preceded by the text, 'source: ' along with a count of the number of artists leads from that source. Select Concat('source: ',Leadsource) As Source, Count(*) As NumLead From Artists Group by Source 6. Functions CS1222_F2018
Objectives Concatenate text fields Text and data manipulation 12/7/2018 Objectives Concatenate text fields Text and data manipulation Date manipulation Manipulate null values Data type conversion Misc functions 6. Functions CS1222_F2018
Text Functions in MySQL 12/7/2018 Text Functions in MySQL LPad(string, num_char, pad_chars) RPad(string,num_char,pad_chars) Makes a string a certain length (num_char) by adding a certain set of pad characters (pad_chars) to the left (LPad) or right (RPad). 6. Functions CS1222_F2018
Examples =10 Length('Larry King') Left('Larry King',5) 12/7/2018 Examples =10 Length('Larry King') Left('Larry King',5) Right('Larry King',4) Substring('Larry King', 2, 4) Locate('king', 'Larry King') LTrim(' Larry ') RTrim(' Larry ') Trim(' Larry ') Upper('Larry') Lower('Larry') ='Larry' ='King' = 'arry' = 7 = 'Larry ' =' Larry' = 'Larry' = 'LARRY' = 'larry' 6. Functions CS1222_F2018
12/7/2018 SQL examples(1) List the first letters of members’ last name and a count of the number of members for each SELECT Left(lastname,1), Count(*) FROM Members GROUP BY Left(lastname,1) 6. Functions CS1222_F2018
SQL examples(2) Find out which track has the longest track name 12/7/2018 SQL examples(2) Find out which track has the longest track name SELECT Tracktitle FROM Tracks WHERE Length(Tracktitle)=( SELECT Max(Length(Tracktitle)) FROM Tracks) 6. Functions CS1222_F2018
12/7/2018 SQL examples(3) For any artist whose name begins with ‘The ‘, list the name formatted as: Rolling Stones, The SELECT Concat(Right(artistName,Length(artistName)- 4), ', The' ) AS NewName FROM Artists WHERE Left(artistName,4) = 'The ‘ NewName ——————— Neurotics, The Bullets, The Kicks, The 6. Functions CS1222_F2018
12/7/2018 SQL Example (4) Report a list of all of the domains that are used by members for email. The domain is the part of the email address after the @ SELECT Right(email, Length(email)- locate('@',email)) FROM Members WHERE email IS NOT NULL 6. Functions CS1222_F2018
Objectives Concatenate text fields Text and data manipulation 12/7/2018 Objectives Concatenate text fields Text and data manipulation Date manipulation Manipulate null values Data type conversion Misc functions 6. Functions CS1222_F2018
Date Manipulation in MySQL 12/7/2018 Date Manipulation in MySQL 6. Functions CS1222_F2018
MySQL Date_Format Format string may include literals 12/7/2018 MySQL Date_Format Format string may include literals Enclose entire format string in quotes. 6. Functions CS1222_F2018
12/7/2018 DATEDIFF(expr1,expr2) DATEDIFF(expr1,expr2) returns the number of days between the start date expr1 and the end date expr2. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation. mysql> SELECT DATEDIFF('1997-12-31 23:59:59','1997-12-30'); -> 1 mysql> SELECT DATEDIFF('1997-11-30 23:59:59','1997-12-31'); > -31 6. Functions CS1222_F2018
MySQL Date_Format ADDDATE('2004-12-01',INTERVAL 1 YEAR) '2005-12-01' 12/7/2018 MySQL Date_Format ADDDATE('2004-12-01',INTERVAL 1 YEAR) '2005-12-01' ADDDATE('2004-12-01',INTERVAL 60 DAY) '2005-01-30' ADDDATE('2004-12-01',INTERVAL -3 MONTH) '2004-09-01' DATE_FORMAT('2004-12-01','%M %e, %Y') 'December 1, 2004' DATE_FORMAT('2004-12-01','The %D of %M') 'The 1st of December' 6. Functions CS1222_F2018
Date Manipulation Example(1) 12/7/2018 Date Manipulation Example(1) List the names and birthdays of all members with June birthday SELECT lastname, firstname, birthday FROM Members WHERE Month(birthday)=6 6. Functions CS1222_F2018
Date Manipulation Example(2) 12/7/2018 Date Manipulation Example(2) List each artist name and that artist’s one-year anniversary date. SELECT artistName, AddDate(entrydate, Interval 1 Year) AS Anniversary FROM Artists 6. Functions CS1222_F2018
Date Manipulation Example(3) 12/7/2018 Date Manipulation Example(3) Report the age in days of members from Georgia. Select lastname, firstname, birthday, To_Days(Now())-To_days(birthday) As AgeInDays From Members Where region='GA' 6. Functions CS1222_F2018
Date Manipulation Example(4) 12/7/2018 Date Manipulation Example(4) Report the artistname and entry date of each artist in mm-dd-yyyy format. Select artistname, entrydate, Date_Format(entrydate, '%m-%d-%Y') As Entered From Artists 6. Functions CS1222_F2018
Objectives Concatenate text fields Text and data manipulation 12/7/2018 Objectives Concatenate text fields Text and data manipulation Date manipulation Manipulate null values Data type conversion Misc functions 6. Functions CS1222_F2018
Handling Nulls in MySQL 12/7/2018 Handling Nulls in MySQL IsNull() returns true or false depending on if expression is null IsNull(expression) IfNull() reports replacement value if expression is null IfNull(expression, display_if_expression_is_null) 6. Functions CS1222_F2018
12/7/2018 Example 1 List the web address of each artist and whether or not the web address is null. Select WebAddress, IsNull(WebAddress) As Is_It_Null From Artists 6. Functions CS1222_F2018
12/7/2018 Example 2 List the web address of each artist. If the web address is null, list ‘No website.‘ Select webaddress, IfNull(WebAddress,'No website') From Artists 6. Functions CS1222_F2018
Objectives Concatenate text fields Text and data manipulation 12/7/2018 Objectives Concatenate text fields Text and data manipulation Date manipulation Manipulate null values Data type conversion Misc functions 6. Functions CS1222_F2018
Data type Conversions in MySQL 12/7/2018 Data type Conversions in MySQL MySQL automatically handles datatype conversions Select Concat(trackTitle, ':', lengthSeconds) From Tracks Where titleID = 4 6. Functions CS1222_F2018
Objectives Concatenate text fields Text and data manipulation 12/7/2018 Objectives Concatenate text fields Text and data manipulation Date manipulation Manipulate null values Data type conversion Misc functions 6. Functions CS1222_F2018
12/7/2018 Simple Case 6. Functions CS1222_F2018
Simple Case Example Select Artistname, Region, Case Region 12/7/2018 Simple Case Example Select Artistname, Region, Case Region When 'NC' Then 'South' When 'VA' Then 'South' When 'IL' Then 'Midwest' When 'VT' Then 'New England' Else 'Somewhere Else' End As Area From Artists Artistname Region Area -------------------------------- --------------- -------------- The Neurotics NC South Louis Holiday IL Midwest Word IN Somewhere Else Sonata VA South The Bullets TX Somewhere Else Jose MacArthur CA Somewhere Else Confused GA Somewhere Else The Kicks NY Somewhere Else Today ONT Somewhere Else 21 West Elm VT New England Highlander OH Somewhere Else 6. Functions CS1222_F2018
Searched Case Syntax SELECT Field, Field, CASE 12/7/2018 Searched Case Syntax SELECT Field, Field, CASE WHEN Field | Expression comparison Value | Field | Expression THEN result ELSE result END As alias FROM Table 6. Functions CS1222_F2018
12/7/2018 Searched Case List the first two tracks of each title, identifying short 1st tracks and long 1st tracks. Select TrackNum, TrackTitle, LengthSeconds, Case When TrackNum=1 And LengthSeconds<240 Then 'Short 1st' When TrackNum=1 And LengthSeconds>480 Then 'Long 1st' Else 'Another Track' End as Eval From Tracks Where TrackNum<3 6. Functions CS1222_F2018
12/7/2018 Greatest(num1, num2,…) List the largest of the following numbers: 3,5,7,9 Select Greatest(3,5,7,9) 6. Functions CS1222_F2018
12/7/2018 Least(num1, number2,…) List any tracks that lack either an mp3 or Real Audio recording Select trackTitle, mp3, realAud From Tracks Where Least(mp3, realAud)=0 6. Functions CS1222_F2018
12/7/2018 FORMAT(X,D) Formats the number X to a format like '#,###,###.##', rounded to D decimals, and returns the result as a string. If D is 0, the result will have no decimal point or fractional part. mysql> SELECT FORMAT(12332.123456, 4); -> '12,332.1235‘ mysql> SELECT FORMAT(12332.1,4); -> '12,332.1000' mysql> SELECT FORMAT(12332.2,0); -> '12,332' 6. Functions CS1222_F2018
12/7/2018 Example Report the name and yearly base of each salesperson formatted with commas and two decimal places Select Concat(firstname, ' ', lastname), Format(base*52 * 5, 2) as 'Yearly Salary' From SalesPeople 6. Functions CS1222_F2018
Summary Text functions Concatenation: Concat, Concat_WS 12/7/2018 Summary Text functions Concatenation: Concat, Concat_WS String length: Length Substring extract: Left, Right, Substring Substring manipulation LTrim, RTrim, Trim, Upper, Lower Substring search: Locate 6. Functions CS1222_F2018
Summary (Cont.) Date manipulation Handle Null values: IsNULL, IfNULL 12/7/2018 Summary (Cont.) Date manipulation Now, Date, day, month,year…. AddDate, DateDiff,SubDate Handle Null values: IsNULL, IfNULL Misc functions Case, Greatest, Least, Format 6. Functions CS1222_F2018