Saturday, October 28, 2023

Materialized Views

Introduction

Common, frequent queries against a database can become expensive. When the same query is run again and again, it makes sense to ‘virtualize’ the query. Materialized views address this need by enabling common queries to be represented by a database object that is continuously updated as data changes. 

A View...

  • is a derived relation defined in terms of stored base relations (generally tables) 
  • defines a SQL transformation from a set of base tables to a derived table; this transformation is typically recomputed / re-compiled every time the view is referenced to in a query 
  • when created, does not compute any results nor does it change how data is stored or indexed
  • is a saved query on tables of a DB 
  • is referenced to, in queries, as if it were a table

Example:

CREATE VIEW user_purchase_summary AS SELECT
  u.id as user_id,
  COUNT(*) as total_purchases,
  SUM(purchases.amount) as lifetime_value
FROM users u
JOIN purchases p ON p.user_id = u.id;

Every time a query referencing view/s is executed, it first computes the results of the view, and then computes the rest of the query using those results.

A Materialized View...

  • takes a regular view and materializes it by upfront computing and storing its results in a “virtual” table 
  • is like a cache, i.e. a copy of the data that can be accessed quickly
  • is a regular view “materialized” by storing tuples of the view in the database
  • can have index structures and hence database access to materialized views can be much faster than recomputing the view

Example:

CREATE MATERIALIZED VIEW user_purchase_summary AS SELECT
  u.id as user_id,
  COUNT(*) as total_purchases,
  SUM(CASE when p.status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_purchases
FROM users u
JOIN purchases p ON p.user_id = u.id;

A regular view is a saved query, and, a materialized view is a saved query along with its results stored as a table.

Implications of materializing a view

  1. When referenced in a query, a materialized view is not recomputed as the results are pre-stored and hence querying materialized views tends to be faster
  2. Because it’s stored as if it were a table, indexes can be built on the columns of a materialized view
  3. Once a view is materialized, it is only accurate until the underlying base relations are modified. The process of updating a materialized view in response to changes in underlying is called view maintenance.

A “view” is an anchored perspective on changing inputs, results are constantly changing as the underlying data changes. Materialization just implies that the transformation is done proactively. So, "materialized views" should update automatically.

However, in practice, some databases need materialized views to be manually refreshed and others have implemented automatic updates, albeit with limitations. 

Note: MySQL does not support materialized view as of now. Oracle, Snowflake, MongoDB, Redshift, PostgreSQL all others do.

Materialized views are used...

  • when SQL query is known ahead of time and needs to be repeatedly recalculated
  • primarily for caching the results of extremely heavy and complex queries that cannot be run frequently as regular views
  • as ability to define (using SQL) any complex transformation of data in DB, and let the DB maintain the results in a “virtual” table. when low end-to-end latency is required between when data originates to when it is reflected in a query
  • when low-latency query response times with high concurrency or high volume of queries is expected

Use of materialized views in...

Applications: Incrementally updated materialized views can be used to replace the caching and denormalization traditionally done to “guard” OLTP databases from read-side latency and overload. Instead of waiting for a query and doing computation to get the answer, we are now asking for the query upfront and doing the computation to update the results as the writes (creates, updates and deletes) come in. This inverts the constraints of traditional database architectures, allowing developers to build data-intensive applications without complex cache invalidation or denormalization.

Analytics: ELT bulk loads raw data into a warehouse and then transforms it via some complex SQLs. The transformation may use regular views (i.e. no caching - used when it is not overly slow), or cached tables built from the results of a SELECT query (used when regular views slow down the queries due to re-computations), or incrementally updated table/s (but user is responsible for writing the update strategy).

OR, use the fourth option i.e.

Use "materialized views", always remain more up-to-date, more automated and less error-prone to cached tables (the end user burden of deciding when and how to update is minimized). 

Monday, July 10, 2017

Ethereum mining on AWS


  • Ethereum mining works only on g2.2xlarge or g2.8xlarge instances with Ubuntu 14.04 or later
  • Port 30303 must be opened for both TCP and UDP connections from `anywhere` (in security group settings)
  • Default Ubuntu available with ec2 is minimal i.e. some drm files required for the OS to see GPU drivers are missing. SSH into your machine and run following steps to fix this:
> sudo apt-get install linux-generic  
(Click OK for default option/s when prompted)
> sudo reboot
  • Download CUDA drivers for ec2 instances (use Nvidia units). Working with .deb package (instead of .run) is easier (local or network makes no difference) 
> wget http://developer.download.nvidia.com/compute/cuda/7_0/Prod/local_installers/rpmdeb/cuda-repo-ubuntu1404-7-0-local_7.0-28_amd64.deb

(Newer versions are available here)

> sudo dpkg -i <cuda repo package>
> sudo apt-get update
> sudo apt-get install cuda
  • Run the following command to check driver is installed: 
> lshw -c video
  • A line that starts with "Configuration:" should mention "...driver=nvidia...", if it doesn't search carefully or try reboot. 
  • If you see "...driver=nouveau..." instead of "...driver=nvidia..." then something is wrong - google how to get rid of it and reinstall cuda.
  • Build geth from source, refer here 
  • run geth to allow it to catch up on the chain: 
> ~/go-ethereum/build/bin/geth
  • install ethminer from cpp-ethereum dev PPAs, refer here 
  • Use following command to check the current hash rate (~6 MH/s) and benchmark ethminer to check that your system is in order: 
> ethminer -G -M 
  • When geth catches up on the blockchain, use the following command to generate a new account: 
> ~/go-ethereum/build/bin/geth account new
  • start geth again with RPC enabled by using command-line below 
> ~/go-ethereum/build/bin/geth --rpc
  • Execute following command to start ethminer
> ethminer -G
  • If using larger g2 instance with 4 GPUs, ethminer needs to be started 4 times. Each time adding a "--opencl-device <0..3>" argument
  • Check logs carefully, ethminer should be getting work packages from geth and be "mining a block"

Sunday, December 27, 2015

How to...

Make YouTube videos run faster

Open Google Chrome
Ctrl + Shift + J - opens Developer Tools, ensure you are on Console tab
On the prompt copy and paste script below:

document.getElementsByTagName("video") [0].playbackRate = 2.5

Instead of playbackRate = 2.5, you can set any other floating number between 1.00 to 4.00

Create a rss feed for "The Thlog"

https://thethlog.blogspot.com/feeds/posts/default?alt=rss

Replace "thethlog" with name of any blog on blogspot, use it for another blog hosted on blogspt. Now, add it to a feed URL to an RSS reader (e.g. Feedly) OR be more creative with GPT.


Saturday, March 21, 2015

Sybase 12.5 to Sybase 15.5 migration - differences that I learnt about

1. Login triggers were introduced in ASE 15.0. A regular ASE stored procedure can automatically executed in background on successful login by any user.

2. Fast bcp is allowed for indexed tables in ASE 15.0.2 and above. bcp works in one of the two modes

  • Slow bcp - logs all the row inserts made, is slower and is used for tables that have one or more index
  • Fast bcp - only page allocations are logged, used for tables without indexes, used when fastest speed possible is required, can be used for tables with non-clustered indexes
3. sp_displaylogin displays when and why a login was locked & also when you last logged in. 

4. Semantic partitions/smart partitioning: ASE 15 makes large databases easy to manage and more efficient by allowing you to divide tables into smaller partitions which can be individually managed. You can run maintenance tasks on selected partitions to avoid slowing overall performance, and queries run faster because ASE 15's smart query optimizer bypasses partitions that don't contain relevant data 

5. With large data sets, filing through a mountain of results data can be difficult. ASE 15's bi-directional scrollable cursors make it convenient to work with large result sets because your application can easily move backward and forward through a result set, one row at a time. This especially helps with Web applications that need to process large result sets but present the user with subsets of those results 

6. Computed columns: Often applications repeat the same calculation over and over for the same report or query. ASE 15 supports both virtual and materialized columns based on server calculations. Columns can be the computed result of other data in the table, saving that result for future repeated queries 

7. Functional indexes: When applications need to search tables based on the result of a function, performance can suffer. Functional indexes allow the server to build indexes on a table based on the result of a function. When repeated searches use that function, the results do not need to be computed from scratch 

8. Plan viewer in the form of a GUI: Plans for solving complicated queries can become very complex and make troubleshooting performance issues difficult. To make debugging queries simpler, ASE 15 provides a graphical query plan viewer that lets you visualize the query solution selected by ASE's optimizer.

9. In ASE 15.0, Update statistics and sp_recompile are not necessary after index rebuild

10. ASE 15 allows to assign two billion logical devices to a single server, with each device up to 4 Tb in size. It supports over 32,767 databases, and the maximum size limit for an individual database is 32 terabytes, extending the maximum storage per ASE server to over 1 million terabytes!

11. As of release 12.5.1, all changes to data cache are dynamic

12. ASE 15.0 and later versions no longer use vdevno. i.e. the disk init syntax doesn't need to mention the vdevno parameter. 

13. Disk init syntax in 12.5 expects size parameter in K, M, and G only. From 15.0 and onwards, T (Terabyte) can be specified. 
Also, pre 15.0; the maximum size of a device was 32GB 

14. The configuration parameter ?default database size? was static in ASE 12. In ASE 12.5, it was made dynamic. 
For ASE 15.0, the below table is specified by Sybase. 
Logical Page Size 2K 4K 8K 16K 
Initial default database size 3MB 4 MB 8 MB 16 MB 
All system tables, initially 1.2 MB 2.4 MB 4.7 MB 9.4 MB

15. The auto database extension was introduced in 12.5.1 and supported later versions.

16. The Dump/Load Database and Dump/Load Tran syntax differ from version 12.5.0.3 and 12.5.2(and hence later versions) (See sybooks for more information. The compression levels 1-9 were introduced.) 

17. ASE 12.5.0.3 and earlier versions used to allow only one tempdb in the server. But all the later versions allow creation of multiple temporary databases. 

18. Before 15.0, after changing a database option we need to use that database and do checkpoint on it. But ASE15.0 doesn't need this. 

19. Restricting proxy authorization is available in 12.5.2 and later releases only. 

20. From version 12.5.2 and onwards, cache creation is made dynamic (sp_cacheconfig [cachename [,"cache_size [P|K|M|G]?] It was static earlier. 

21. Till 12.5.2, backing up a database with password was not possible. ASE 12.5.2 and later allow dump database with passwd. 

22. Cross platform dumps and loads were introduced in ASE 12.5.3 

23. MDA tables (Monitoring and Diagnostic Tables) are available in 12.5.3 and later releases. 

24. Row Level Locking: In ASE 15.0 all the system tables were converted into datarows format.

25. Group By without Order By

Saturday, February 28, 2015

The Land Acquisition debate

A debate with my dear friend Neelkamal, on facebook, is about the #LandAcquisition bill (Act of 2015) of India.

The questions and thoughts Neel has about the #LandAcquisition bill:


Here is what I have to say about it - part 1 and part 2.

Land acquisition bill should be about "right to fair compensation against (someone's) property being acquired". Fair is what seems good to all parties involved. 4X is not fair any more to the farmers, having figured that the land would later sell for perhaps 40x or even more (fetched by the land acquired for "affordable housing" and other such projects). The fairness ends there. Economics is not taught, it just prevails.

A misconception amongst many is that all farmers have several hectares of land and hence they become rich by selling land. Fact is that for 1 such huge land bank holder there are hundreds with little land, tilling which they earn bread. 

They are uneducated and can't afford, for their children, the education promised by our constitution to every child (BTW! Do you consider it as a freebie as well?). Having sold their land they will end up as unskilled labour, the class of society that seldom make their ends meet. It is a class of the society that ends up feeling deprived and often ends up into a negative spiral and may even lead to crime. 

Those who have enough land to become affluent, have experienced that though they had money but they never knew what to do with it and ended up wasting the fortune. Their children ended up as spoilt youth. Once bitten, twice shy. 

Why was an ordinance required as first step to this law? Was it because the Govt believed that they force it in the lower house, for the opposition would not be able to a thing about it? Kudos to those who walked-out, a walkout is a very polite means of showing disagreement and is massively effective. It is a clear expression that those who walkout WILL NOT BE A PART TO IT while the law could still be formed. Applaud them for the befitting response, do not criticize them.

Respected FM responded to this question - "Bharat ke pehlay pradhaan-mantri (Shri J. L. Nehru) 70 ordinance laye thay". 
Kintu prashan to ye hai ki iss adhya-aadesh ki kya aavashyakta thi? Yeh na batayein ki kon kitnay adhya-aadesh kab or kis prakaar laya. 

A hugely illiterate India has been a nation of farmers (70% till a few years ago, still not less than 60%), independent earners. Land acquisition not supported with education and professional skills development is turning poor farmers towards begging and crime. 

BTW, I will be glad if we (as a nation) view farming as entrepreneurship or at least as a cottage industry and support it with various funds and means? Further, why does farming not fit the concept of "Make in India"?

Let us bring colour to the "fairness", the now bills suggests that when Govt is acquiring the land for defence purpose the consent of the farmer is not necessary. The bill presented by the previous Govt was more reasonable, it suggested only when a state of emergency is declared (already) any land can be acquired for defence without the consent of the affected farmer(s).
Add insult to injury, the compensation is said to be paid (by the now proposed bill) not when the recipient signs on receipt but when the Govt signs on the release of compensation.

A commonality amongst revolts around the world is the peasants, they are not the opposition nor do they sit as those in power - but they are the real power. Give them the due.


Neel's reply:

What I have to say on this:

 Neel, please appreciate that land for a farmer is not an asset that they have maintained for generations to make money. Unlike many non-farming land-hoarders (look at the farmhouses around spewing affluence), land for a farmer is the only means to earn a living and manage a respectful life. 

किसान के खेत उसकी सम्पन्नता का प्रतीक नहीं अपितु उसके आर्थिक रूप से समर्थ बनने का एक या एकमात्र साधन हैं। आज के परिपेक्ष में देशभक्ति का माप आर्थिक, शारीरिक या किसी और प्रकार के सामर्थ्य का त्याग तो नहीं होना चाहिए। 

How are then - you, I, respected PM, the rich of rich or anyone else more or less patriotic as compared to any farmer? 

आज देशभक्ति मापने के लिए यह देखें कि कौन देश के किन संसाधनो पर किस प्रकार का और कितना बोझ डाल रहा है और वह देश को कितना और कितने प्रकार से समृद्ध बना रहा है। आप पाएंगे कि किसान भी बाकि सभी जितना देशभक्त है। 

I think the question to be asked is not "Why are you (the farmers) not convinced to give away the land?", the right question is "How can we convince our brothers to give their land (or even skin) for the purpose we say is National Development?". A few points to take care of in my opinion are:

1. Bring agriculture on "Make in India" agenda. Treat farmers as entrepreneurs. (As I said earlier, give to them "the due".)

2. Farming is a means of living that has helped generations of farmers sustain. When you ask them to part of from their land, give them not only the "now" fair value of it but also give to them (a) skills that bring to them somewhat similarly sustaining means of living and (b) give them the value of land that will be, until they acquire such a means of living - it may really be 4x or 400x.

3. If one is not convinced, do not force them. Alter your plans instead (a little at least) where possible and let them know that they are being dealt with compassion.

4. Publish and explain the plans for which one's land is being acquired. Make sure that the land is being used as it was asked for and make transparent a deviation and its reasons if it occurs.

Some will be convinced soon, some later a very few perhaps never - but we need to work on a long term solution that brings people together not divide people into classes (them vs. us, they are farmers, we are middle class etc etc etc). 

Invariably everyone needs to takes the above in perspective, lest the said ordinance turns into "The Land Grab Bill".

Human greed? The coats of rich and powerful will be auctioned to fetched 50x the original price (if 10 L is believed) and the land of the poor can be grabbed instead at a dictated price!