Index

SQL

Previously in my fresher time, I rarely write SQL, I always use ORM to wrap SQL.
But time past and too much abstraction bites me.
So I decide to only write SQL from now, no more ORM for me.
But if there is any cool ORM for Go, I guess I try.

This guide is not kind of guide which cover all cases.
Just my little tricks when I work with SQL.

Stay away from database unique id

Use UUID instead.

Stay away from database timestamp

Stay away from all kind of timestamp, timestamp of MySQL or any database.
Just use int64 then pass the timestamp in service layer not database layer.

Why? Because time and date and location are too much complex to handle.
In my business, I use timestamp in milliseconds.
Then I save timestamp as int64 value to database.
Each time I get timestamp from database, I parse to time struct in Go with location or format I want.
No more hassle!

Use index

You should use index for faster query, but not too much.
Don't create index for every fields in table.
Choose wisely!

For example, create index in MySQL:

CREATE INDEX `idx_timestamp`
    ON `user_upload` (`timestamp`);

Be careful with NULL

If compare with field which can be NULL, remember to check NULL for safety.

-- field_something can be NULL

-- Don't
SELECT *
FROM table
WHERE field_something != 1

-- Do
SELECT *
FROM table
WHERE (field_something IS NULL OR field_something != 1)

Thanks

Feel free to ask me via email