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:
Single-row One single value One single LEFT('Maria',2) → 'M 1 value in → 1 value
Functions (one row) value (one row) a' out
Multiple values in →
Multi-row Multiple values One single SUM(30,10,20,40) →
1 summarized
Functions (multiple rows) summary value 100
output
[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.
[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:
This logical division promotes efficient data workflows: engineers prepare the
dataset, analysts interpret and use it.
[04:53]
Course Structure Announcement and Next Steps
o Practical examples and scenarios illustrating when and why to use specific
functions.
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.
[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
[03:10]
Changing String Case: UPPER and LOWER Functions
SQL example:
sqlCopy
[06:01]
Removing Unwanted Spaces: The TRIM Function
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
Syntax:
sqlCopy
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
o Plain text
Example:
o Input: "Maria" → 5
o Input: "350" → 3
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 n characters from the left (start) of the string.
Example:
Input: "Maria", LEFT(string, 2) → "Ma"
RIGHT(string, n)
Extracts the last n 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
sqlCopy
[25:48]
Closing Notes
Convert all
UPPER characters to UPPER(string) Useful for data standardization
uppercase
Convert all
LOWER characters to LOWER(string) Useful for data standardization
lowercase
Count number of
Includes letters, digits, spaces,
LENGTH characters in a LENGTH(string)
symbols
string
Extract characters
LEFT LEFT(string, n) Extracts n leftmost characters
from start of string
Extract characters
RIGHT RIGHT(string, n) Extracts n rightmost characters
from end of string
Extract characters
SUBSTRIN SUBSTRING(string,
from specific Flexible extraction from middle
G start_pos, length)
position
[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:
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:
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.
The instructor highlights the practical usefulness of this function to transform and
Round
Rounds
numer
up or
ic
down
values
based on
ROUN to ROUND(3.5
3.52 digit
D specifi 16, 2)
immedia
ed
tely after
decim
rounding
al
position
places
No
rounding
ROUND(3.5
3.5 if next
16, 1)
digit
below 5
Rounds
ROUND(3.5 to
4
16, 0) nearest
integer
Conve
rts a Converts
numb negative
er to s to
its positive,
ABS ABS(-10) 10
absolu leaves
te positives
(positi unchang
ve) ed
value
[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]
Hierarchical order: Year > Month > Day > Hour > Minute > Second
Summary:
Hours, Minutes,
TIME All major DBMS
Seconds
Oracle, PostgreSQL,
TIMESTAMP/ Date + Time (including
MySQL, SQL Server
DATETIME 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:
[06:50]
Format and Casting: Change how the date/time is displayed or its data type.
[08:13]
Descr
Cate
Functions Included iptio
gory
n
Extrac
t
parts
Part
DAY(), MONTH(), YEAR(), DATEPART(), DATENAME(), of
Extra
DATE_TRUNC(), EOMONTH() dates
ction
or
trunc
ate
Conve
Form rt or
atting forma
& FORMAT(), CONVERT(), CAST() t
Casti date/t
ng ime
types
Add/
subtra
Calcul ct or
DATEADD(), DATEDIFF()
ations find
interv
als
Valida
te if a
Valida date
ISDATE()
tion string
is
valid
[09:06]
o DAY() returns 20
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]
Examples:
Syntax:
[18:06]
Examples:
Syntax:
[22:32]
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).
[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:
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)
[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
quarte String (same as specified (function
Integer (1-4)
r integer) typically truncates
to month level in
practice)
String (same as
week Integer (1-53) Not applicable
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.
[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 vs. Casting in SQL
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:
Switching formats allows creation of different regional date styles such as:
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
[15:20]
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]
Examples:
[20:42]
Converts
String to
CONVERT(int, '123') int numeric string
Integer
to int
[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]
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
[29:15]
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 date/time formatting with style numbers, CONVERT is preferred over CAST.
[30:10]
Introduction to Date Calculations (Brief Mention)
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().
SQL Server defaults to ISO 8601 date format but supports customizing formats for
different locales and styles.
CONVERT() bridges formatting and casting specifically for date/time, with a rich
set of style codes.
Combining these tools, SQL users can efficiently standardize, convert, and present
date and number data for diverse business and reporting needs.
Term Definition
[00:00]
Introduction to the DATEADD Function
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
2. Interval: Specifies how much to add or subtract (integer, positive for add,
negative for subtract).
[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]
[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.
sqlCopy
For example, Order #1 shipped 4 days after ordering, Order #3 took 15 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.
[18:22]
Use Case: Handling Data Quality Issues with Date Strings
Converting string values to date can cause errors if some values are invalid.
Attempting a direct cast:
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
Call to action: Viewers are encouraged to like, subscribe, share, and comment to
support the content creation.