Skip to main content

String, Date, and Time Operations

In SQL, string, date, and time functions are essential for transforming, comparing, and formatting data. While the SQL standard defines common operations, each database introduces its own variations and extensions.

These functions can generally be grouped into:

  • String operations – manipulation and formatting of textual data.
  • Date & time operations – extraction, comparison, and transformation of temporal values.

String Operations

String operations allow us to manipulate and query textual data stored in columns like CHAR, VARCHAR, TEXT, etc.

Common String Functions

OperationExampleDescription
Concatenation`'Hello''World'`Joins two strings. (`` is standard SQL operator)
LengthCHAR_LENGTH('Hello')Returns length of string
UppercaseUPPER('sql')'SQL'Converts to uppercase
LowercaseLOWER('SQL')'sql'Converts to lowercase
SubstringSUBSTRING('Database' FROM 5)'base'Extracts substring
PositionPOSITION('b' IN 'Database')5Finds index of substring
TrimTRIM(BOTH 'x' FROM 'xxxabcxxx')'abc'Removes characters from sides
ReplaceREPLACE('cat', 'c', 'b')'bat'Replaces substring
OverlayOVERLAY('abcdef' PLACING 'xyz' FROM 3)'abxyzf'Replaces part of string (PostgreSQL)

Case Sensitivity of Strings

DatabaseCase SensitivityExplanation
MySQLCase-insensitive by default for most string comparisonsMySQL uses a case-insensitive collation (e.g., utf8_general_ci, where ci means “case-insensitive”). You can make it case-sensitive by using a binary collation (e.g., utf8_bin).
PostgreSQLCase-sensitive by default'abc' = 'ABC' returns false. To perform case-insensitive comparisons, use functions like ILIKE or convert both strings using LOWER() or UPPER().
SQLiteCase-insensitive by default for ASCII characters'abc' = 'ABC' is true. However, case-insensitivity for non-ASCII characters depends on the collation.
OracleCase-sensitive'abc' = 'ABC' is false unless you use functions like UPPER() or case-insensitive collations.
SQL ServerDepends on the collation settingThe default collation (SQL_Latin1_General_CP1_CI_AS) is case-insensitive. You can change it using a case-sensitive collation.

Quoting Strings

DatabaseString QuotingNotes
MySQLBoth single ' and double " quotes are allowed (by default in ANSI mode)'abc' and "abc" are equivalent, but it’s recommended to use single quotes for strings and double quotes for identifiers in ANSI-compliant SQL.
PostgreSQLOnly single quotes ' for stringsDouble quotes " are used only for identifiers (e.g., column or table names).
SQLiteSingle quotes ' for stringsDouble quotes are for identifiers.
OracleSingle quotes ' for stringsDouble quotes for identifiers.
SQL ServerSingle quotes ' for stringsDouble quotes can be used for identifiers if QUOTED_IDENTIFIER is ON.

Example comparison

MySQL:

SELECT 'Hello' = "hello";  -- true (case-insensitive by default)

PostgreSQL:

SELECT 'Hello' = 'hello';  -- false
SELECT LOWER('Hello') = LOWER('hello'); -- true

Concatenation Differences Across Databases

DatabaseOperatorFunctionExample
Standard SQL``
MySQLCONCAT()YesCONCAT('A', 'B') → 'AB'
PostgreSQL`andCONCAT()`
SQL Server+Yes'A' + 'B' → 'AB'
Oracle``

Note: SQL Server treats || as bitwise OR, not concatenation. MySQL’s CONCAT() returns NULL if any argument is NULL; CONCAT_WS() (with separator) ignores NULLs.

Examples:

-- Get first 3 characters
SELECT SUBSTRING('Database', 1, 3); -- MySQL, SQL Server
SELECT SUBSTRING('Database' FROM 1 FOR 3); -- PostgreSQL, Oracle

-- Find position
SELECT POSITION('a' IN 'Database'); -- All major databases

-- Replace substring
SELECT REPLACE('Data Science', 'Data', 'Computer'); -- 'Computer Science'

Case Conversion

SELECT UPPER('sql'); -- 'SQL'
SELECT LOWER('SQL'); -- 'sql'

All databases support these, but Oracle also provides INITCAP('hello world') → 'Hello World'.

Trimming and Padding

SELECT TRIM('   SQL   '); -- 'SQL'
SELECT LTRIM(' SQL'); -- 'SQL'
SELECT RTRIM('SQL '); -- 'SQL'

SELECT LPAD('5', 3, '0'); -- '005' (MySQL, Oracle, PostgreSQL)
SELECT RPAD('5', 3, '0'); -- '500'
FunctionMySQLPostgreSQLSQL ServerOracle
TRIM
LPAD / RPAD✗ (use RIGHT('000'+col, n))
INITCAP

Date and Time operations

SQL provides rich functionality for working with date and time values. These operations are essential for reporting, analytics, and data transformation.

Common Date/Time Data Types

DatabaseDate TypeTime TypeDateTime/Timestamp Type
Standard SQLDATETIMETIMESTAMP
PostgreSQLDATETIME, TIMETZTIMESTAMP, TIMESTAMPTZ
MySQLDATETIMEDATETIME, TIMESTAMP
SQL ServerDATETIMEDATETIME, DATETIME2, SMALLDATETIME
OracleDATE (includes time)TIMESTAMPTIMESTAMP WITH TIME ZONE

Extracting Date Parts

Standard SQL:

EXTRACT(YEAR FROM order_date);
EXTRACT(MONTH FROM order_date);
EXTRACT(DAY FROM order_date);

Differences:

DatabaseFunctionExample
PostgreSQLEXTRACT()EXTRACT(DOW FROM order_date) → weekday
MySQLYEAR(order_date), MONTH(order_date)YEAR('2025-10-11') → 2025
SQL ServerDATEPART(year, order_date)DATEPART(month, order_date)
OracleEXTRACT(YEAR FROM order_date) or TO_CHAR(order_date, 'YYYY')

Current Date/Time

FunctionDescriptionExample
CURRENT_DATEReturns current date'2025-10-11'
CURRENT_TIMEReturns current time'14:30:00'
CURRENT_TIMESTAMPReturns current date & time'2025-10-11 14:30:00'
NOW()Non-standard but widely supported'2025-10-11 14:30:00'

Differences:

DatabaseFunctionNotes
PostgreSQLCURRENT_DATE, NOW()Both supported
MySQLNOW(), CURRENT_TIMESTAMPSynonyms
SQL ServerGETDATE(), SYSDATETIME()SYSDATETIME() more precise
OracleSYSDATE, SYSTIMESTAMPEquivalent to current date/time

Date Arithmetic

Add or Subtract Intervals:

OperationExampleResult
Add daysorder_date + INTERVAL '7 DAY'Adds 7 days
Subtract daysorder_date - INTERVAL '2 DAY'Subtracts 2 days
Differenceend_date - start_dateNumber of days (PostgreSQL, Oracle)

Database Differences:

OperationPostgreSQLMySQLSQL ServerOracle
Add interval+ INTERVAL '1 day'+ INTERVAL 1 DAYDATEADD(day, 1, date)date + 1
Differenceend - startDATEDIFF(end, start)DATEDIFF(day, start, end)end - start
Extract partEXTRACT(YEAR FROM date)YEAR(date)DATEPART(year, date)EXTRACT(YEAR FROM date)

Formatting Dates

OperationExampleResult
Format dateTO_CHAR(order_date, 'YYYY-MM-DD')'2025-10-11'
Convert string to dateTO_DATE('2025-10-11', 'YYYY-MM-DD')2025-10-11

Differences:

DatabaseFunctionExample
PostgreSQLTO_CHAR(), TO_DATE()TO_CHAR(NOW(), 'DD Mon YYYY')
MySQLDATE_FORMAT(date, '%d %b %Y')DATE_FORMAT(NOW(), '%Y-%m-%d')
SQL ServerFORMAT(date, 'dd MMM yyyy')FORMAT(GETDATE(), 'yyyy-MM-dd')
OracleTO_CHAR(), TO_DATE()TO_CHAR(SYSDATE, 'DD-MON-YYYY')

Extracting Weekday, Week, or Quarter

OperationPostgreSQLMySQLSQL ServerOracle
WeekdayEXTRACT(DOW FROM date) (0=Sunday)DAYOFWEEK(date) (1=Sunday)DATEPART(WEEKDAY, date)TO_CHAR(date, 'D')
Week numberEXTRACT(WEEK FROM date)WEEK(date)DATEPART(WEEK, date)TO_CHAR(date, 'WW')
QuarterEXTRACT(QUARTER FROM date)QUARTER(date)DATEPART(QUARTER, date)TO_CHAR(date, 'Q')

Time Operations

Extracting Time Components:

OperationExample
EXTRACT(HOUR FROM time_col)Extracts hour
EXTRACT(MINUTE FROM time_col)Extracts minute
EXTRACT(SECOND FROM time_col)Extracts seconds

Differences:

  • MySQL: HOUR(time_col), MINUTE(time_col), SECOND(time_col)
  • SQL Server: DATEPART(hour, time_col)
  • Oracle: use TO_CHAR(time_col, 'HH24:MI:SS')

Time Arithmetic

OperationPostgreSQLMySQLSQL ServerOracle
Add hourstime + INTERVAL '2 HOUR'ADDTIME(time, '02:00:00')DATEADD(hour, 2, time)time + (2/24)
Differenceend - startTIMEDIFF(end, start)DATEDIFF(second, start, end)end - start

Summary Table

CategoryStandard SQLPostgreSQLMySQLSQL ServerOracle
String concatCONCAT()CONCAT()CONCAT()CONCAT(), +CONCAT()
SubstringSUBSTRING()SUBSTRING()SUBSTRING()SUBSTRING()SUBSTR()
LengthCHAR_LENGTH()CHAR_LENGTH()CHAR_LENGTH()LEN()LENGTH()
Date add+ INTERVAL+ INTERVAL+ INTERVALDATEADD()+ N
Date diff--DATEDIFF()DATEDIFF()-
Current dateCURRENT_DATECURRENT_DATECURDATE()GETDATE()SYSDATE
Date formatCAST/TO_CHARTO_CHAR()DATE_FORMAT()FORMAT()TO_CHAR()

Key Takeaways

  1. String functions are largely standardized but have differences in syntax (|| vs + vs CONCAT()).

  2. Date arithmetic differs widely — SQL Server and MySQL use special functions (DATEADD, DATEDIFF), while PostgreSQL and Oracle support arithmetic directly.

  3. Formatting (TO_CHAR, DATE_FORMAT, FORMAT) is highly database-specific.

  4. Timezone-aware types (TIMESTAMPTZ, DATETIMEOFFSET) are handled differently:

    • PostgreSQL: TIMESTAMPTZ
    • SQL Server: DATETIMEOFFSET
    • Oracle: TIMESTAMP WITH TIME ZONE
  5. Always consult documentation when migrating SQL logic across databases — especially for string concatenation, date formatting, and interval arithmetic.