惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
大猫的无限游戏
大猫的无限游戏
博客园 - 聂微东
Jina AI
Jina AI
The Cloudflare Blog
V
Visual Studio Blog
博客园_首页
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 【当耐特】
爱范儿
爱范儿
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
博客园 - 司徒正美
阮一峰的网络日志
阮一峰的网络日志
Last Week in AI
Last Week in AI
V
V2EX
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 叶小钗
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
T
Tailwind CSS Blog
博客园 - Franky

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Why I Stopped Using Raw SQL Date Functions and Switched t...
Chris Lloyd · 2026-05-05 · via DEV Community

Chris Lloyd Fallaria

It Started With a Bug

When I was building VMMS — a voucher management system
for government offices — everything worked fine locally.

MySQL. Clean queries. Fast results.

Then I deployed to a server running MariaDB.

Half my charts broke.


The Problem

I had written date queries like this all over the codebase:

// This breaks on MariaDB
DB::table('voucher_transactions')
    ->selectRaw('MONTHNAME(created_at) as month, COUNT(*) as total')
    ->groupByRaw('MONTH(created_at), MONTHNAME(created_at)')
    ->get();

Enter fullscreen mode Exit fullscreen mode

MONTH() and MONTHNAME() are MySQL functions. They work
fine on MySQL but behave differently on MariaDB — especially
when combined with GROUP BY.

The result? Months showing up in the wrong order.
Duplicate entries. Missing data.


Why This Happens

MySQL and MariaDB have diverged over the years. They share
a lot of syntax but handle certain functions differently —
especially around date grouping and ordering.

The safe rule is: if you want your app to work on both,
don't rely on database-specific date functions.


The Fix — Pull the Data and Use Carbon

Instead of doing date calculations in SQL, I pulled the
raw data and used Carbon to handle everything in PHP:

// DB-agnostic approach
$rows = VoucherTransaction::where('user_id', $userId)
    ->whereYear('created_at', $year)
    ->whereNull('deleted_at')
    ->get(['created_at', 'status']);

$byMonth = [];
foreach ($rows as $row) {
    $m = (int) $row->created_at->format('n');
    $status = strtolower($row->status);
    $byMonth[$m] = $byMonth[$m] ?? ['accomplished' => 0, 'rejected' => 0];
    if ($status === 'accomplished') $byMonth[$m]['accomplished']++;
    if ($status === 'rejected')     $byMonth[$m]['rejected']++;
}

ksort($byMonth);

Enter fullscreen mode Exit fullscreen mode

Then to get the month name I used Carbon instead of
MONTHNAME():

$monthName = Carbon::create($year, $m, 1)->format('F');
// Returns "January", "February", etc.
// Works the same on MySQL and MariaDB

Enter fullscreen mode Exit fullscreen mode


Building the Full Year Chart

For charts that need all 12 months — even empty ones —
I use range(1, 12) and fill in zeros for months with
no data:

return collect(range(1, 12))->map(function ($m) use ($byMonth, $year) {
    $d = $byMonth[$m] ?? ['accomplished' => 0, 'rejected' => 0];
    return [
        'month'        => Carbon::create($year, $m, 1)->format('F'),
        'accomplished' => $d['accomplished'],
        'rejected'     => $d['rejected'],
    ];
});

Enter fullscreen mode Exit fullscreen mode

This guarantees all 12 months always appear in the chart
— even if there's no data for some months. Clean and
predictable.


What About Performance?

You might be thinking — isn't pulling all rows and
processing in PHP slower than doing it in SQL?

For most applications — yes, SQL aggregation is faster.

But in practice for this use case:

  • The data is filtered by user and year first
  • The result set is small (max 365 rows per year per user)
  • The PHP processing is negligible

If you're dealing with millions of rows this approach
needs rethinking. But for typical business applications
it's fast enough and the portability is worth it.


Other Carbon Tricks I Use in VMMS

Comparing dates without time:

// Use DATE() in SQL to avoid time comparison issues
->whereRaw('DATE(deadline) >= ?', [$now->toDateString()])
->whereRaw('DATE(deadline) <= ?', [$now->copy()->addDays(7)->toDateString()])

Enter fullscreen mode Exit fullscreen mode

Calculating days left:

$deadline = Carbon::parse($t->deadline)->startOfDay();
$daysLeft = (int) $now->copy()->startOfDay()->diffInDays($deadline, false);

Enter fullscreen mode Exit fullscreen mode

The false parameter makes diffInDays return negative
numbers for past dates — useful for overdue detection.

Calculating processing time:

$minutes = Carbon::parse($row->process_initiate)
    ->diffInMinutes(Carbon::parse($row->process_accomplished));

Enter fullscreen mode Exit fullscreen mode


The Lesson

Don't assume your local MySQL behavior will match
production. If your app might run on MariaDB, PostgreSQL,
or any other database — keep your date logic in PHP
with Carbon and use only standard SQL for filtering.

It's a small habit that saves a lot of debugging time.


About VMMS

This and many other lessons came from building VMMS —
a complete voucher management system for government
offices, companies, and educational institutions.

🔴 Live demo: https://vmms-app-production.up.railway.app/login

Available on Gumroad:
👉 https://getvmms.gumroad.com/l/zeroqz

Happy to answer any questions in the comments! 🚀