Dwarves
Memo
Type ESC to close search bar

Sql Practices Orm Vs Plain Sql

Definition

Factors that affects the technique decision

Practice

Use ORM for almost case, with DEEP understanding the library. Raw is supported in ORM Use Raw and SQL Generator for some special case

Indexing

The best technique for improve performance in database is to use indexes well. A index is a data structure that the database uses to correlate value to the rows where these values occur in a given column. An index provides an easy way for the database to find values more quickly than the brute-force method of searching the whole table from top to bottom. Index can also help an Update or Delete statement by finding the rows quickly (primary key)

Misunderstanding when using indexes

Using INSERT, UPDATE, DELETE, the database has to update the index data structures for that table to be consistent so that our subsequent searches use these indexes to find the right set of rows reliably.

There’s no benefit to creating indexes that we don’t use

Practice

Indexing base on the requirement or what queries are important to optimize

Measure the application code to find out the bottle-neck. Don’t make informed decisions without information.

Make Index with condition

CREATE UNIQUE INDEX line_items_prod_var_null_idx

ON line_items (product_id)

WHERE variant_id IS NULL

Rebuild the index data

Over time, as we update and delete rows, the indexes may become fragmented overtime - SQL system tool

Rounding Errors

Fractional Number(float, decimal) is common type in db: money, measurement: length, weight, capacity, temperature, time. infinite precision VS finite precision: 1/3 vs 0.33

IEEE 754 represents floating-point numbers in a base-2 format. The Float data can’t represent exactly in binary. The reason is we try to convert base-10 to base-2

See more reference at Oracle’s document.

Practice

Use Numeric or Decimal in SQL for fixed-precision fractional numbers

Query Practice

Get row with Greatest value per group. Follow the Single-Value rule to build the query. The rows in each group are those rows with the same value in the column or columns you name after GROUP BY. Every column in the select-list of a query must have a single value row per row group.

Search a simple text

Practice

Reference