MySQL Functions, JSON, and Date Cheatsheet

now, date_add, date_sub, date_format, timestampdiff, json_extract, json_set, json_object, concat, coalesce, and case in MySQL.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## date and time functions
Get the current date and time
SELECT NOW(), CURRENT_DATE(), CURRENT_TIME();

# Return current timestamp values.

Add an interval to a date
SELECT DATE_ADD(NOW(), INTERVAL 7 DAY) AS one_week_from_now;

# Calculate a future date or time.

Subtract an interval
SELECT DATE_SUB(NOW(), INTERVAL 30 DAY) AS thirty_days_ago;

# Calculate a relative date in the past.

Format dates for display
SELECT DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s') AS created_at_fmt FROM orders LIMIT 5;

# Render a datetime using format specifiers.

Compute the difference between two timestamps
SELECT TIMESTAMPDIFF(MINUTE, created_at, NOW()) AS age_minutes FROM sessions;

# Calculate age or duration.

## json and string functions
Extract a value from JSON
SELECT JSON_EXTRACT(settings, '$.notifications.email') AS email_enabled FROM user_preferences;

# Read a path inside a JSON document.

Update a JSON path
UPDATE user_preferences
SET settings = JSON_SET(settings, '$.theme', 'dark')
WHERE user_id = 42;

# Write or replace a value inside a JSON document.

Build JSON in a query
SELECT JSON_OBJECT('id', id, 'email', email) AS user_json FROM users LIMIT 5;

# Construct a JSON object from scalar values.

Concatenate strings
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM contacts;

# Join scalar values into one string.

Use COALESCE for fallback values
SELECT COALESCE(display_name, full_name, email) AS label FROM users;

# Return the first non-NULL expression.

Map values with CASE
SELECT id,
  CASE status
    WHEN 'paid' THEN 'Paid'
    WHEN 'pending' THEN 'Pending'
    ELSE 'Other'
  END AS status_label
FROM orders;

# Transform values into labels inside a query.

Recommended next

No recommendations yet.