SQL 2
SQL 2
Definition of function: A built-in code block in SQL that accepts an input value, processes it,
and returns an output value after performing some transformation.
SQL functions enable users to systematically interact with data stored in tables to prepare or
analyze it efficiently.
[00:56]
Categories of SQL Functions
SQL functions are broadly categorized into two types based on their input-output behavior:
[01:54]
Nesting SQL Functions: Composition and Execution Order
SQL allows combining multiple functions by nesting; the output of one function serves as the
input to another.
Example given:
3. LENGTH('ma') returns 2
Conceptual analogy: Data flows through processing stages (like factory stations), with each
function modifying the intermediate result.
o Wrap it inside parentheses and place inside the next function call.
o Continue wrapping if more functions are added.
LENGTH(LOWER(LEFT(Maria,2)))
[04:02]
Subcategories of SQL Functions Based on Data Type and Usage
Within the two main functional categories, functions are further subdivided:
- String functions
Single-row - Numeric functions Used for cleaning, transforming, and preparing
functions - Date & Time functions individual data values before aggregation
- Null-handling functions
[04:26]
Role of SQL Functions in Data Engineering and Data Analysis
Single-row functions:
Multi-row functions:
o Primarily used by Data Analysts for data summarization and reporting tasks through
aggregate and window functions.
This logical division promotes efficient data workflows: engineers prepare the dataset,
analysts interpret and use it.
[04:53]
Course Structure Announcement and Next Steps
The course begins with string functions, teaching how to manipulate character data values
in SQL.
[00:00]
Summary: Overview of String Data Transformation Functions in SQL
The video focuses on transforming string data using SQL string functions.
Each group addresses different needs: combining strings, character case transformation,
cleansing spaces, replacing values, counting characters, and extracting partial strings.
[00:26]
String Manipulation: Concatenation (CONCAT)
Example use case: Joining first name and last name stored in separate columns into one full
name.
SQL usage:
sqlCopy
sqlCopy
Key Insight: Concatenation aids in data presentation and easier analysis by merging related
string data into one field.
[03:10]
Changing String Case: UPPER and LOWER Functions
Example transformations:
Practical task examples involved transforming a customer's first name entirely to lowercase or
uppercase.
SQL example:
sqlCopy
Conclusion: These functions standardize data for consistency in queries and reports.
[06:01]
Removing Unwanted Spaces: The TRIM Function
Purpose: Eliminate leading and trailing spaces (whitespace) from string values.
Problem overview:
o Strings can have unwanted spaces at the start (leading), at the end (trailing), or both.
TRIM(string) removes all such extra spaces, which is essential for cleaning dirty or
inconsistent input data.
sqlCopy
sqlCopy
Key Insight: The TRIM function is fundamental for data cleansing to avoid errors caused by
invisible whitespaces.
[11:21]
Replacing Characters: The REPLACE Function
Purpose: Substitute all occurrences of a specified substring within a string with another
substring.
Syntax:
sqlCopy
REPLACE(string, old_substring, new_substring)
Usage examples:
Input: "123-456-7890"
Output: "123/456/7890"
Input: "[Link]"
Output: "[Link]"
Conclusion: REPLACE is a versatile function widely used for formatting and data correction.
[14:39]
Calculations on Strings: LENGTH Function
Purpose: Calculates the total number of characters in a string, including letters, digits,
punctuation, and spaces.
o Plain text
Example:
o Input: "Maria" → 5
o Input: "350" → 3
sqlCopy
Insight: Useful for validating data format, identifying anomalies, and supporting substring
extraction.
[16:29]
Extracting Parts of Strings: LEFT, RIGHT, and SUBSTRING Functions
LEFT(string, n)
Extracts the first 𝑛 characters from the left (start) of the string.
Example:
Input: "Maria", LEFT(string, 2) → "Ma"
RIGHT(string, n)
Extracts the last 𝑛 characters from the right (end) of the string.
Example:
Input: "Maria", RIGHT(string, 2) → "ia"
Both require the full string and the number of characters to extract.
o SQL:
sqlCopy
Handling variable length strings with SUBSTRING can be tricky; to include all characters
starting at a position to end of string, use a large number or dynamically calculate length via
the LENGTH function.
sqlCopy
SUBSTRING(TRIM(first_name), 2, LENGTH(TRIM(first_name)))
Key Insight:
o LEFT and RIGHT are ideal for extracting from fixed ends.
[22:54]
Practical SQL Examples and Tips
o Use TRIM inside SUBSTRING to ensure unwanted spaces do not affect substring
extraction.
sqlCopy
A variety of string manipulation functions have been covered which provide powerful tools to
clean, format, combine, and extract string data in SQL.
Encouragement given to support the channel through likes, subscriptions, and sharing.
Substitute old
REPLACE(string, Can also remove characters by
REPLACE substring with new
old_substring, new_substring) replacing with empty string
one
Extract characters
LEFT LEFT(string, n) Extracts 𝑛 leftmost characters
from start of string
Extract characters
RIGHT RIGHT(string, n) Extracts 𝑛 rightmost characters
from end of string
[00:00]
This segment introduces the topic of transforming numeric values using two simple SQL
functions: ROUND and ABS (absolute value). The main focus is on explaining how
the ROUND function operates, using the example number 3.516. Key points include:
Applying ROUND with two decimal places means keeping two digits after the decimal point.
The third decimal digit (6 in this case) determines if the second digit will round up or stay.
Since the third digit (6) is greater than 5, the value rounds up, turning 3.516 into 3.52.
The function effectively "cuts off" or resets digits beyond the specified decimal place.
[00:33]
Further details about the ROUND function are explained with different decimal places for
rounding:
Rounding to one decimal place: The second digit (1) after the decimal decides whether to
round up the first digit (5).
Since 1 is less than 5, there is no rounding up, so the number becomes 3.5.
Digits after the maintained decimal place are reset to zero (effectively removed).
Rounding to zero decimals: This means rounding the value to the nearest integer.
The first digit after the decimal (5) determines if the integer part (3) should round up.
Since it is 5 (or above), the integer part rounds up to 4, with all decimal digits removed.
The overall mechanism of how the ROUND function decides whether to round up or stay the
same depending on the digit following the rounding precision is emphasized.
[01:33]
The instructor transitions to how the ROUND function works in SQL practically:
An example using static values (not directly querying a database table) demonstrates the
function.
This allows practicing on fixed numbers like 3.516 without requiring table data.
This method is used to conveniently understand and test the numeric functions.
[02:00]
A live SQL example of the ROUND function is demonstrated:
The output correctly shows 3.52, as explained earlier (since the third decimal digit 6 causes
rounding up).
This confirms the theoretical explanation with practical SQL code and output verification.
[02:33]
Further SQL executions test the ROUND function with different decimal places:
Decimal
Input Output Explanation
Places
Key takeaway: The rounding logic strictly aligns with the digit immediately after the
rounding position.
[03:07]
The video introduces the second numeric function: ABS (absolute value):
This function converts any negative number into its positive counterpart.
Explains that if the number is already positive, the function returns it as is.
If a data set has logically invalid negative sales figures, using ABS can normalize all values to
positive.
Rounds up
Round or down
numeric based on
values to ROUND(3.516, digit
ROUND 3.52
specified 2) immediately
decimal after
places rounding
position
No
ROUND(3.516, rounding if
3.5
1) next digit
below 5
Rounds to
ROUND(3.516,
4 nearest
0)
integer
Converts
Converts
a
negatives
number
to positive,
ABS to its ABS(-10) 10
leaves
absolute
positives
(positive)
unchanged
value
The instructor highlights the practical usefulness of this function to transform and sanitize
numerical data in databases.
[04:04]
The conclusion wraps up the numeric functions section:
Only two simple but important functions — ROUND and ABS — have been covered.
The next video will shift focus to manipulating date and time data in SQL, suggesting the
continuity of learning SQL functions.
Key Insights
The ROUND function uses the digit immediately after the indicated decimal place to
determine rounding behavior: if it is 5 or above, the number rounds up; otherwise, it
remains.
Setting the decimal places to zero (0) rounds the number to the nearest integer.
The ABS function ensures all numbers are positive, which is crucial when handling
numeric data that logically cannot have negative values (e.g., sales figures).
Practicing with static values inside SQL allows learners to understand and verify
function behaviors without needing actual database tables.
Mastery of these foundational numerical functions prepares one for more complex SQL
operations, such as date/time functions, which are hinted as the next topic.
Conclusion
[00:00]
The video begins with a foundational overview of date and time concepts in SQL.
Date represents calendar dates like "August 20th, 2025," composed of three parts:
[01:12]
o Hours: 0 to 23
o Minutes: 0 to 59
o Seconds: 0 to 59
[01:44]
o TIMESTAMP (in Oracle, PostgreSQL, MySQL) or DATETIME (in SQL Server), which
includes year, month, day, hour, minute, second, and fractions of seconds.
Hierarchical order: Year > Month > Day > Hour > Minute > Second
Summary:
Hours, Minutes,
TIME All major DBMS
Seconds
Oracle, PostgreSQL,
Date + Time (including
TIMESTAMP/DATETIME MySQL, SQL Server
fractions of seconds)
(DATETIME)
[02:44]
o Order Date and Shipping Date columns use DATE type, storing only date without
time.
o Creation Date column uses DATETIME/ TIMESTAMP type, storing full date and time
including milliseconds.
Querying shows date-only columns return only year, month, day, whereas datetime columns
include hours, minutes, seconds, and fractions.
[04:18]
The three primary sources for date/time values in SQL queries are:
1. Stored dates inside the database, e.g., order date columns.
2. Hardcoded date strings (static values inside queries), e.g., '2025-08-20'. These are
fixed and used for calculations or filters.
3. Current date and time via SQL functions, chiefly the GETDATE() function, which
returns the current date and time at query execution.
GETDATE() accepts no parameters and returns a DATETIME value. It's frequently used
throughout SQL operations.
[06:50]
Format and Casting: Change how the date/time is displayed or its data type.
[08:13]
Part
DAY(), MONTH(), YEAR(), DATEPART(), DATENAME(), DATE_TRUNC(),
Extraction
Formatting
FORMAT(), CONVERT(), CAST()
& Casting
Validation ISDATE()
[09:06]
Simple and straightforward functions that accept one DATE or DATETIME parameter and
return an integer representing the corresponding part.
o MONTH() returns 8
Syntax summary:
DAY(date)
MONTH(date)
YEAR(date)
Practical examples demonstrated querying these from the creation_time column to extract the
year, month, and day as integers.
[12:21]
DATEPART(part, date) allows extracting various date/time components beyond day, month,
and year, including:
Examples:
Syntax:
DATEPART(part,date)
[18:06]
Retrieves the name of a specified date part instead of a number (as in DATEPART).
Examples:
For parts like year or day of month, it still returns the numeric value but as a string.
Syntax:
DATENAME(part,date)
[22:32]
Truncates the date/time to a specified part by resetting lower granularity parts to default
values.
The function accepts part and date parameters similar to DATEPART and DATENAME.
Truncation
Result Explanation
Part
'2025-08-20
minute Seconds reset to zero
18:55:00'
'2025-08-20
hour Minutes and seconds reset
18:00:00'
'2025-08-20
day Time parts reset
00:00:00'
'2025-08-01
month Day reset to 1, time reset
00:00:00'
Widely used for data aggregation at different granularities (group by year, month, day).
[29:11]
Grouping by exact creation time yields many rows with little aggregation (each second is
unique).
Truncating to month or year allows grouping to fewer entries with summarized counts:
Result Example (# of
Granularity Explanation
rows)
[31:09]
Examples:
o EOMONTH('2025-08-20') → '2025-08-31'
o If the input date is already the last day, it returns the same date.
[33:09]
No direct function like EOMONTH() for first day, but can be generated by truncating at
the month level:
DATE_TRUNC(’month’,date)
To show only the date (no time), cast the result to DATE:
sqlCopy
This method combined with EOMONTH() allows retrieval of start and end of month values in
reports.
[34:37]
Filtering Data:
sqlCopy
WHERE MONTH(order_date) = 2
Best practice: filter using integer-valued functions (MONTH(), YEAR()), not string-valued
(DATENAME()) for performance.
[39:41]
Output Data
Function(s) Description
Type
Human-readable name of
DATENAME() String parts (month names,
weekday names)
Date truncated to
DATETIME /
DATE_TRUNC() specified part, includes
TIMESTAMP
time
[40:37]
o Use DATENAME().
If you want to extract other parts like week number, quarter, hour, minute, second:
o Use DATEPART().
Use DATE_TRUNC() for truncating or grouping data by a specific level of detail for analysis.
[41:39]
Truncates date to
quarter Not speci
String (same as
quarter Integer (1-4) (function typically
integer)
truncates to mont
in practice)
String (same as
day Integer (1-31) Truncates date to
integer)
String (same as
week Integer (1-53) Not applicable
integer)
String (e.g.,
weekday Integer (1-7) Not applicable
"Monday")
String (same as
hour Integer (0-23) Truncates time to
integer)
Note: Not all parts apply exactly the same to DATE_TRUNC() due to truncation logic.
[42:06]
The video provides downloadable SQL scripts demonstrating all functions and date parts
combined in one query for practice.
The example uses GETDATE() as the input date to show outputs of all extraction methods
simultaneously.
Encourages hands-on learning to familiarize with output formats and function behaviors.
[43:05]
Conclusion
The tutorial covers manipulating date and time in SQL focusing on 13 key functions
categorized as extraction, formatting, calculation, and validation.
The instructor invites viewers to subscribe, like, and share for future SQL tutorials.
00:04]
Date format consists of date and time components such as year, month, day, hour, minute,
and second, which are represented by a combination of numbers and characters.
Characters like dashes (“-”) or spaces between components are part of the date format and
must be represented explicitly in SQL formatting.
Format specifiers are the symbolic codes used in SQL to represent parts of the date/time:
o Hour: two digits, usually HH for 24-hour format; can also use lowercase for 12-hour
format.
[01:38]
SQL Server adopts ISO 8601, so all date values in SQL databases default to Year-Month-
Day ordering.
[03:10]
Formatting changes the appearance or presentation of data without altering its underlying
data type.
o The FORMAT() function in SQL is used for this purpose, taking parameters for value,
format string, and optionally culture (regional formatting).
o The CONVERT() function can also perform formatting but uses a style
number instead of a format string.
Casting changes the data type of a value (e.g., string to integer, date to string).
o Casting actually changes the stored type; formatting just changes how it looks.
[04:06]
o Using culture parameter (optional) can specify localization, e.g., "ja-JP" for Japanese
style or "fr-FR" for French, which affects date, time, and number formatting.
Format specifiers are customizable and can be used for both dates and numbers:
o Numbers: "N" formats as numeric with commas, "C" for currency (adds dollar
sign), "P" for percentage (adds percent sign).
o Dates: Specifiers such as DD, DDD, DDDD provide day digits, abbreviated day
name, and full day name respectively.
[07:56]
Day formats:
Month formats:
o USA: MM-DD-YYYY
o Europe: DD-MM-YYYY
[10:26]
Combine static text, format specifiers, and functions to build custom date/time strings.
Example construction:
o Start with string “day ” (static), concatenated with short day name (DDD), abbreviated
month (MMM), quarter (Q1, Q2, etc.), year, 12-hour time (hh:mm:ss), and AM/PM
designator (tt).
Example pattern:
Copy
This approach provides flexibility to generate unconventional date/time formats for reporting
or display.
[15:20]
Example: Sales aggregated by month can display months as abbreviated names plus two-
digit year (e.g., Jan 25).
sqlCopy
FROM sales_orders
Practical insight: Unifying date formats across different data sources (CSV files, APIs,
databases) is crucial for consistent analytics and reporting.
[17:18]
SQL provides a comprehensive set of format specifiers for both dates and numbers.
Date/time format specifiers are case sensitive and each corresponds to precise date/time
parts or textual representations.
Number format specifiers include options for numeric (N), currency (C), percentage (P), and
cultural variants.
Resource available: Pre-prepared queries listing all possible date and number format
specifiers, which users can run live in SQL to explore outputs.
[18:47]
o Optional style parameter allows formatting dates and strings, especially useful for
date/time string formats.
Examples:
[20:42]
Converts
String to Integer CONVERT(int, '123') int numeric string to
int
sales_orders datetime
Returns string
DateTime to
CONVERT(varchar, formatted
Formatted varchar
creation_time, 32) as MM-DD-
String (US)
YYYY
[24:17]
SQL Server supports many culture codes that influence how date and numbers are
formatted.
Example cultures: Japan, Korea, France, Germany, Arabic, Russian, and more.
[25:15]
Syntax:
sqlCopy
CAST(value AS data_type)
Key difference from CONVERT: Does not include support for formatting or styles; strictly for
type conversion only.
Examples:
sqlCopy
Supports Supports
Function Notes
Casting Formatting
CAST and CONVERT allow conversion between any data types (string, int, date, datetime,
varchar).
FORMAT only converts any type to a string with desired formats for presentation.
For number formatting (currency, percent, numeric), user should rely on FORMAT, as
CONVERT does not support number formatting.
For date/time formatting with style numbers, CONVERT is preferred over CAST.
[30:10]
The video concludes with a brief mention that the next topic deals with date calculations and
mathematical operations on dates using two SQL functions.
Summary
SQL offers powerful tools for formatting and casting dates, times, and numbers, with
functions like FORMAT(), CAST(), and CONVERT().
Formatting manipulates appearance without changing data type; casting changes the data
type itself.
Case sensitivity is critical in format specifiers (e.g., uppercase M for month vs lowercase m for
minutes).
SQL Server defaults to ISO 8601 date format but supports customizing formats for different
locales and styles.
Combining these tools, SQL users can efficiently standardize, convert, and present date and
number data for diverse business and reporting needs.
Term Definition
Format A symbolic string that indicates how a date/time or number component should
Specifier be displayed. Case sensitive.
Casting Converting a value from one data type to another (e.g., string to integer).
Formatting Changing the display representation of a value without modifying its data type.
Style
Numeric codes passed to CONVERT() to specify date/time string formats.
(CONVERT)
[00:00]
Introduction to the DATEADD Function
The DATEADD function is used to add or subtract a specific time interval—such as years,
months, or days—to or from a given date.
Example: Starting with the date August 20th, 2025, adding 3 years results in August 20th,
2028 (only the year changes).
Adding months works similarly; for example, adding 2 months changes August 20th, 2025, to
October 20th, 2025.
Adding days works similarly; adding 5 days changes August 20th to August 25th, 2025.
[01:06]
DATEADD can subtract time intervals too, even though it's named "add."
For example, subtracting 3 years from August 20th, 2025 yields August 20th, 2022.
Key insight: DATEADD manipulates the year, month, and day components of a date by
adding or subtracting the specified interval seamlessly.
[01:36]
DATEADD Syntax Breakdown
1. Part (datepart): Specifies which part to manipulate (e.g., year, month, day).
2. Interval: Specifies how much to add or subtract (integer, positive for add, negative for
subtract).
Whether the interval is positive or negative controls if the function adds or subtracts time.
[03:03]
Practical Examples Using DATEADD on Order Dates
Adding 2 years to each order date consistently produces new values 2 years later.
Adding 3 months shifts dates forward by 3 months, e.g., January becomes April, February
becomes May.
Subtracting 10 days affects the day part accordingly, e.g., an order from January 15th
becomes January 5th.
[04:38]
Summary of DATEADD Utility
[04:57]
Introduction to DATEDIFF Function
It outputs the number of years, months, or days between two dates, depending on the
specified part.
Example dates: Order Date = August 20th, 2025; Shipping Date = February 1st, 2026.
[05:16]
Calculating months returns 3 months difference (from August 2025 to February 2026).
Key insight: DATEDIFF provides a numeric difference in the specified unit, simplifying
calculating durations or intervals.
[06:14]
DATEDIFF Syntax Details
Parameters:
Example: DATEDIFF(year, OrderDate, ShipDate) returns how many full years have passed.
This function assumes chronological order—start date should be earlier than end date.
[07:13]
Task: Calculating Employees’ Age Using DATEDIFF and GETDATE
Employee age is calculated as the number of years between the birthdate and the current
date (using GETDATE() to get the current date).
Example query:
sqlCopy
FROM Employees;
[09:07]
Task: Calculating Average Shipping Duration in Days per Month
Select order ID, order date, and ship date from the sales orders table.
Shipping duration is computed as the difference in days between order date and ship date
using:
sqlCopy
For example, Order #1 shipped 4 days after ordering, Order #3 took 15 days.
To find the average shipping duration per month, aggregate by month (extracted from the
order date), then calculate average days:
sqlCopy
FROM SalesOrders
GROUP BY MONTH(OrderDate);
Result summary:
January ~7
February ~7
March ~5
Key insight: DATEDIFF is powerful for deriving time-based analytics like shipping durations.
[11:48]
Task: Calculate Number of Days Between Each Order and Previous Order
Requires identifying the previous order date for each order using the LAG window function:
sqlCopy
FROM SalesOrders;
After retrieving previous order dates, the difference in days is computed with DATEDIFF:
sqlCopy
Example results:
2 2025-01-05 2025-01-01 4
3 2025-01-10 2025-01-05 5
Key insight: Combining window functions with date functions yields powerful time-gap
analysis.
[14:57]
Introduction to ISDATE Function – Date Validation
Returns:
Usage example:
sqlCopy
[16:55]
ISDATE Format Limitations
ISDATE only recognizes standard date formats; non-standard formats like '20-08-2025'
(day-month-year) return 0.
It can recognize year-only formats such as '2025' as a valid date (assumed as January 1st,
2025).
[18:22]
Use Case: Handling Data Quality Issues with Date Strings
Converting string values to date can cause errors if some values are invalid.
sqlCopy
CAST(OrderDateString AS DATE)
To avoid errors, use ISDATE to filter or conditionally cast only valid dates:
sqlCopy
SELECT OrderDateString,
FROM Orders;
This approach highlights data quality problems (invalid dates appear as NULL), enabling
easier data cleaning.
[21:20]
Filtering and Identifying Invalid Date Entries
Using ISDATE in a WHERE clause helps to filter out invalid date strings:
sqlCopy
SELECT *
FROM Orders
WHERE ISDATE(OrderDateString) = 0;
[22:18]
Summary of Covered Date and Time Functions in SQL
[23:16]
Conclusion and Next Steps
With a clear understanding of date/time functions, the viewer is prepared to handle common
date manipulations in SQL effectively.
The next tutorial will focus on subqueries for complex SQL queries.
Call to action: Viewers are encouraged to like, subscribe, share, and comment to support the
content creation.