fullstack_webdev

Code and notes from Full stack web developer path, LinkedIn Learning.

View on GitHub

5. Strings

05_01 About SQL Strings

SELECT 'Here''s a single quote mark.';
-- Standard SQL
SELECT 'This' || ' & ' || 'that' ;

-- MySQL uses a `CONCAT` function
SELECT CONCAT('This', ' & ', 'that');

-- Microsoft SQL uses a non standard operator +
SELECT 'This' + ' & ' + 'that';
SUBSTR(string, start, length);
LENGTH(string);
TRIM(string);
UPPER(string);
LOWER(string);

05_02 Finding length of a string

-- Get length of string zebra
SELECT LENGTH('zebra') AS LEN;

-- Returns the cities by length of their names and lists the length of their names in longest to smallest city order
SELECT Name, Length(Name) AS Len, Population FROM City ORDER BY Len Desc, Name;

05_03 Selecting part of a string

-- Starting position is 6, so string is returned
SELECT SUBSTR('this string',6);
-- Specify the number of characters to return as third argument, will return str
SELECT SUBSTR('this string',6,3);

-- E.g. There's a release data in the album table, we could get all of the released date column from album table as follows:
SELECT released FROM album ORDER BY released; -- Entries are just strings

-- To transform a date in a column given as 1959-08-17 we could use substr in the following manner, notice year is from 1 and 4 char, then from 6th index to 2 chars i.e. 6 and 7 are month and from 9 to 2 chars i.e. 9 and 10 are Day
SELECT released,
    SUBSTR(released, 1, 4) AS Year,
    SUBSTR(released, 6, 2) AS Month,
    SUBSTR(released, 9, 2) AS Day
    FROM album ORDER BY released
;

05_04 Removing Spaces

-- TRIM removes spaces from both the sides
SELECT TRIM('    string    ');

-- LTRIM removes spaces from the string on the left side, not from the end
SELECT LTRIM('    string    ');

-- RTRIM removes spaces from the string on the right side, not from the beginning
SELECT LTRIM('    string    ');

-- Specify a custom character to remove from string, instead of spaces
SELECT TRIM('....string....', '.');

05_05 Folding Case

--Not equal
SELECT 'StRiNg' = 'string';

-- Equal
SELECT LOWER('StRiNg') = LOWER('string');

-- Equal
SELECT UPPER('StRiNg') = UPPER('string');

SELECT UPPER(Name) FROM City ORDER BY Name;
SELECT LOWER(Name) FROM City ORDER BY Name;