Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Advanced MySQL Patterns for Data Analysis and Transformation

Tech Nov 26 12

Fixing Import Encoding Issues

When loading CSV files containing multi-byte characters, ensure the source file is saved as UTF-8. If the dataset uses legacy GBK encoding, convert the target table before import.

ALTER TABLE client_profiles CONVERT TO CHARACTER SET utf8mb4;

Building Tables from Queries

Derive a new table on the fly using CREATE TABLE ... AS SELECT, transforming columns as needed.

CREATE TABLE client_profiles AS
SELECT 
  user_id,
  age_bracket,
  CASE gender_flag
    WHEN 1 THEN 'Female'
    WHEN 0 THEN 'Male'
    ELSE 'Not Specified'
  END AS gender,
  membership_level,
  registered_at
FROM staging_db.raw_user_data;

Enforcing Precision with DECIMAL

Use CAST to control decimal places in monetary or ratio calculations.

SELECT 
  CAST(
    SUM(monthly_revenue) OVER (ORDER BY report_month) 
    AS DECIMAL(12, 2)
  ) AS cumulative_revenue
FROM financials;

Extracting Substrings

MySQL offers several ways to slice strings.

-- Isolate text before a delimiter
SUBSTRING_INDEX(salary_text, '万/月', 1)

-- Extract a fixed range
SUBSTR(phone_raw, 1, 7)

-- Locate a character, then slice dynamically
SUBSTR(product_sku, 1, INSTR(product_sku, '(') - 1)

Duplicating Table Structures

Create an empty copy of an existing table, then populate it with a representative sample.

CREATE TABLE transaction_subset LIKE retail_orders;

INSERT INTO transaction_subset
SELECT DISTINCT *
FROM retail_orders
LIMIT 50000;

Importing SQL Dumps via Terminal

Restore a database without opening an interactive MySQL session.

mysql -u root -p database_name < /full/path/to/backup.sql

If the file is in the current directory, a relative path works. Otherwise, use an absolute path.

Conditional Counting and Summation

Filter aggregates inline using IF or CASE expressions.

-- Count only specific events
COUNT(IF(action_type = 'purchase', user_id, NULL))

-- Equivalent sum-based approach
SUM(CASE WHEN action_type = 'purchase' THEN 1 ELSE 0 END)

Measuring User Retention

Calculate day-N retention by joining a date sequence to itself.

SELECT 
  base.event_date,
  COUNT(DISTINCT base.user_id) AS active_users,
  COUNT(DISTINCT IF(DATEDIFF(future.event_date, base.event_date) = 1, future.user_id, NULL)) AS next_day_return
FROM (
  SELECT DISTINCT user_id, event_date 
  FROM transaction_subset
) base
LEFT JOIN (
  SELECT DISTINCT user_id, event_date 
  FROM transaction_subset
) future 
  ON base.user_id = future.user_id
  AND future.event_date > base.event_date
GROUP BY base.event_date;

Reusable Logic with Views and CTEs

Encapsulate deduplication logic for cleaner downstream queries.

CREATE VIEW unique_listings AS
WITH ranked AS (
  SELECT 
    *,
    ROW_NUMBER() OVER (
      PARTITION BY company_name, job_title 
      ORDER BY posted_date
    ) AS dup_rank
  FROM job_postings
)
SELECT * FROM ranked WHERE dup_rank = 1;

Computing Percentage of Total

Reference an overall aggregate using a scalar subquery.

SELECT 
  industry,
  sector_revenue,
  total_revenue,
  CONCAT(
    CAST(sector_revenue * 100.0 / total_revenue AS DECIMAL(10, 2)),
    '%'
  ) AS revenue_share
FROM (
  SELECT 
    company_type,
    SUM(salary_floor) AS sector_revenue,
    (SELECT SUM(salary_floor) FROM unique_listings) AS total_revenue
  FROM unique_listings
  GROUP BY company_type
) aggregates
ORDER BY sector_revenue DESC;

Tracking Consecutive Active Days with Variables

Session variables can simulate row-by-row state to measure streaks.

SELECT 
  creator_id,
  MAX(streak_length) AS longest_run
FROM (
  SELECT 
    creator_id,
    activity_date,
    IF(
      creator_id = @prev_id AND DATEDIFF(activity_date, @prev_date) = 1,
      @streak := @streak + 1,
      @streak := 1
    ) AS streak_length,
    @prev_id := creator_id,
    @prev_date := activity_date
  FROM (
    SELECT DISTINCT creator_id, activity_date 
    FROM author_events 
    ORDER BY creator_id, activity_date
  ) sorted
  CROSS JOIN (SELECT @streak := 0, @prev_id := NULL, @prev_date := NULL) init
) streaks
GROUP BY creator_id;

Working with Unix Timestamps

Convert epochs and calculate date deltas.

-- Format a Unix timestamp
FROM_UNIXTIME(contract_started, '%Y-%m-%d')

-- Convert slash-delimited strings to standard dates
SELECT TO_DATE(FROM_UNIXTIME(UNIX_TIMESTAMP('2021/02/11')));

-- Or simply replace separators
SELECT REPLACE('2021/02/11', '/', '-');

Average operating hours and partnership tenure:

SELECT 
  city_code,
  MONTH(operating_date),
  CAST(AVG(uptime_seconds) / 3600 AS DECIMAL(10, 2)) AS avg_daily_hours
FROM partner_ops
WHERE uptime_seconds IS NOT NULL
  AND MONTH(operating_date) = MONTH(CURDATE())
GROUP BY city_code;

SELECT 
  merchant_ref,
  FROM_UNIXTIME(contract_start, '%Y-%m-%d') AS start_date,
  DATEDIFF(CURDATE(), FROM_UNIXTIME(contract_start, '%Y-%m-%d')) AS days_active
FROM partner_ops
GROUP BY merchant_ref;

Month-over-Month Growth Rankings

Compare current-month volume against the prior month and global totals.

WITH city_merchants AS (
  SELECT 
    city,
    merchant_ref,
    COUNT(DISTINCT CASE WHEN MONTH(order_time) = MONTH(CURDATE()) THEN order_id END) AS curr_month_orders,
    COUNT(DISTINCT CASE WHEN MONTH(order_time) = MONTH(CURDATE()) - 1 THEN order_id END) AS last_month_orders,
    COUNT(DISTINCT order_id) AS lifetime_orders,
    RANK() OVER (PARTITION BY city ORDER BY COUNT(DISTINCT order_id) DESC) AS rnk
  FROM order_summary
  GROUP BY city, merchant_ref
)
SELECT 
  city,
  merchant_ref,
  curr_month_orders,
  last_month_orders,
  CAST((curr_month_orders - last_month_orders) * 100.0 / NULLIF(last_month_orders, 0) AS DECIMAL(10, 2)) AS mom_growth_pct,
  lifetime_orders - curr_month_orders AS orders_before_current_month,
  rnk
FROM city_merchants
WHERE rnk <= 10;

Deciles and Categorical Ratios

Slice distributions into buckets and compute conditional rates.

WITH merchant_summary AS (
  SELECT 
    city,
    merchant_ref,
    COUNT(order_id) AS total_orders,
    COUNT(IF(meal_type = 'breakfast', order_id, NULL)) AS breakfast_orders,
    COUNT(IF(meal_type = 'dinner', order_id, NULL)) AS dinner_orders,
    COUNT(shipping_fee) AS shipped_orders,
    COUNT(IF(shipping_fee = 0, order_id, NULL)) AS free_ship_orders
  FROM order_summary
  WHERE MONTH(order_time) = MONTH(CURDATE())
  GROUP BY city, merchant_ref
)
SELECT 
  city,
  merchant_ref,
  total_orders,
  breakfast_orders,
  dinner_orders,
  CONCAT(CAST(free_ship_orders * 100.0 / shipped_orders AS DECIMAL(10, 2)), '%') AS free_shipping_rate,
  NTILE(10) OVER (PARTITION BY city ORDER BY total_orders DESC) AS decile
FROM merchant_summary;

Building Session Paths

Chain sequential events into delimited paths.

WITH deduped AS (
  SELECT 
    visitor_id,
    scene_category,
    ROW_NUMBER() OVER (PARTITION BY visitor_id, scene_category ORDER BY event_time) AS seq
  FROM user_journey
),
ordered_scenes AS (
  SELECT 
    visitor_id,
    scene_category,
    LEAD(scene_category) OVER (PARTITION BY visitor_id ORDER BY event_time) AS next_scene,
    ROW_NUMBER() OVER (PARTITION BY visitor_id ORDER BY event_time) AS path_order
  FROM deduped
  WHERE seq = 1
)
SELECT 
  visitor_id,
  CONCAT(
    scene_category,
    IF(next_scene IS NULL, '', CONCAT('-', next_scene))
  ) AS journey_path
FROM ordered_scenes
WHERE path_order = 1;

Pivoting Flags into Columns

Transform narrow event data into a wide schedule matrix.

SELECT 
  teacher_ref,
  MAX(CASE WHEN weekday_num = '1' THEN 'yes' END) AS monday,
  MAX(CASE WHEN weekday_num = '2' THEN 'yes' END) AS tuesday,
  MAX(CASE WHEN weekday_num = '3' THEN 'yes' END) AS wednesday,
  MAX(CASE WHEN weekday_num = '4' THEN 'yes' END) AS thursday,
  MAX(CASE WHEN weekday_num = '5' THEN 'yes' END) AS friday
FROM teacher_schedule
GROUP BY teacher_ref;

Unpivoting Scores into Rows

Normalize a wide grade table into a tall format.

SELECT pupil_name, 'english' AS subject, english_mark AS score FROM exam_results
UNION ALL
SELECT pupil_name, 'maths' AS subject, maths_mark FROM exam_results
UNION ALL
SELECT pupil_name, 'music' AS subject, music_mark FROM exam_results;

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.