DataCamp SQL Functions
Timestamp Functions in SQL
Higher Precision
SYSDATETIME()SYSUTCDATETIME()SYSDATETIMEOFFSET()
Lower Precision
GETDATE()GETUTCDATE()CURRENT_TIMESTAMP
Datename Function SYNTAX
SELECT
first_name,
last_name,
first_vote_date,
-- Select day of the week from the first vote date
DATENAME(dw,first_vote_date) AS first_vote_dayofweek
FROM voters;
SELECT
first_name,
last_name,
-- Extract the month number of the first vote
DATEPART(MONTH,first_vote_date) AS first_vote_month1,
-- Extract the month name of the first vote
DATENAME(MONTH,first_vote_date) AS first_vote_month2,
-- Extract the weekday number of the first vote
DATEPART(WEEKDAY,first_vote_date) AS first_vote_weekday1,
-- Extract the weekday name of the first vote
DATENAME(WEEKDAY,first_vote_date) AS first_vote_weekday2
FROM voters;
CREATING DATE FROM PARTS SYNTAX
DATEFROMPARTS FUNCTION
SELECT
first_name,
last_name,
-- Select the year of the first vote
YEAR(first_vote_date) AS first_vote_year,
-- Select the month of the first vote
MONTH(first_vote_date) AS first_vote_month,
-- Create a date as the start of the month of the first vote
DATEFROMPARTS(YEAR(first_vote_date), MONTH(first_vote_date), 1) AS first_vote_starting_month
FROM voters;
Find and Search Functions
CHARINDEX()
The syntax is:
CHARINDEX(expression_to_find, expression_to_search [, start_location])SELECT
first_name,
last_name,
email
FROM voters
-- Look for the "dan" expression in the first_name
WHERE CHARINDEX('dan', first_name) > 0
-- Look for last_names that do not contain the letter "z"
AND CHARINDEX('z', last_name) = 0;
2] Function for looking a patter within a string
PATINDEX
PATINDEX('%pattern%', expression)
| pattern | match |
|---|---|
| % | any string of zero or more characters |
| _ | any single character |
| [] | any single character within the range specified in brackets |
SELECT
first_name,
last_name,
email
FROM voters
-- Look for first names that contain one of the letters: "x", "w", "q"
WHERE PATINDEX('%[xwq]%',first_name) > 0;
Comments
Post a Comment