sql / intermediate
Snippet
Safe Data Type Conversion and Fallback Value Handling
This query demonstrates standard scalar functions for type safety and handling missing data. CAST explicitly converts values between compatible SQL data types, while COALESCE returns the first non-NULL argument from left to right, providing a reliable default fallback value for optional fields.
snippet.sql
sql
1
2
3
4
5
SELECTemployee_id,CAST(hire_date AS VARCHAR(10)) AS hire_date_str,COALESCE(phone_number, 'N/A') AS contact_phoneFROM employees;
Breakdown
1
SELECT
Initiates the data retrieval statement.
2
employee_id,
Selects the primary key column without modification.
3
CAST(hire_date AS VARCHAR(10)) AS hire_date_str,
Converts the date data type to a variable-length character string of 10 characters.
4
COALESCE(phone_number, 'N/A') AS contact_phone
Evaluates phone_number and returns 'N/A' if the field contains a NULL value.
5
FROM employees;
Specifies the target table for the query.