Tuesday, November 20, 2012


SQL-What is a View

A View is a "Virtual Table". It is not like a simple table, but is a virtual table which contains columns and data from different tables (may be one or more tables). A View does not contain any data, it is a set of queries that are applied to one or more tables that is stored within the database as an object. After creating a view from some table(s), it used as a reference of those tables and when executed, it shows only those data which are already mentioned in the query during the creation of the View.
View1.JPG

Views are used as security mechanisms in databases. Because it restricts the user from viewing certain column and rows. Views display only those data which are mentioned in the query, so it shows only data which is returned by the query that is defined at the time of creation of the View. The rest of the data is totally abstract from the end user.
Along with security, another advantage of Views is data abstraction because the end user is not aware of all the data in a table.

Uses

We begin with creating 3 tables PRODUCTSCustomer BOOKING. These are fictitious tables for our demo. ThePRODUCTS stores data for a retail shop with a flag column IsSalable based on whose value we treat the products as Salable.
CREATE TABLE PRODUCTS
(ProductID INT PRIMARY KEY CLUSTERED,
ProductDesc VARCHAR(50) NOT NULL,
ManufacturingDate DATETIME,
ExpiryDate DATETIME,
IsSalable BIT,--1 Salable/Active FOR 0 For NonSalable/Passive Product
Price MONEY NOT NULL
)
Next, we have a Customer table which stores UserID and Password details for customers.
CREATE TABLE Customer
(CustID INT IDENTITY(1002,2)PRIMARY KEY CLUSTERED,
 FName VARCHAR(50) NOT NULL,
 LNme VARCHAR(50) NOT NULL,
 UserID VARCHAR(100) NOT NULL,
 Pswd NVARCHAR(100) NOT NULL DEFAULT 'password123'
)
Lastly, I have created a BOOKING table which houses all the bookings from different customers.
CREATE TABLE BOOKING
( BookingID INT IDENTITY(10,2) PRIMARY KEY CLUSTERED,
  ProductID INT REFERENCES dbo.Products(ProductID),
  CustID INT REFERENCES dbo.Customer(CustID),
  DateOfBooking DATETIME NOT NULL,
  QTY INT
)
Next, insert a few records into these tables:
INSERT INTO PRODUCTS VALUES
(1,'Biscuits','2011-09-01 00:00:00.000','2012-09-01 00:00:00.000',1,20),
(2,'Butter','2010-09-01 00:00:00.000','2011-09-01 00:00:00.000',1,30),
(3,'Milk','2011-10-01 00:00:00.000','2011-11-01 00:00:00.000',1,46)

INSERT INTO Customer (FName,LNme,UserID,Pswd)
 VALUES
('Sara','Verma','S.Verma@abc.com','S123'),
('Rick','Singh','G.Singh@xyz.com','G311'),
('Micky','Khera','M.Khera@mno.com','M222')

INSERT INTO BOOKING (ProductID,CustID,DateOfBooking,QTY)
VALUES
(1,1002,'2011-11-01 00:00:00.000',3),
(2,1004,GETDATE(),4),
(3,1006,'2011-10-01 00:00:00.000',2)
Our tables contents look like this. I know the tables are not completely normalized, for now please ignore them, these are simple demo tables.
SELECT * FROM Customer
CustID      FName     LNme    UserID           Pswd
--------- -------- ---------- ---------------  ---------
1002        Sara   Verma      S.Verma@abc.com  S123
1004        Rick   Singh      G.Singh@xyz.com  G311
1006        Micky  Khera       M.Khera@mno.com M222

(3 row(s) affected)

Select * from PRODUCTS

ProductID  ProductDesc  ManufacturingDate       ExpiryDate              IsSalable Price
---------- ------------ ----------------------- ----------------------- --------- -------
1          Biscuits     2011-09-01 00:00:00.000 2012-09-01 00:00:00.000 1         20.00
2          Butter       2010-09-01 00:00:00.000 2011-09-01 00:00:00.000 1         30.00
3          Milk         2011-10-01 00:00:00.000 2011-11-01 00:00:00.000 1         46.00

(3 row(s) affected)

Select * from BOOKING
BookingID   ProductID   CustID      DateOfBooking           QTY
----------- ----------- ----------- ----------------------- -----------
10          1           1002        2011-11-01 00:00:00.000 3
12          2           1004        2011-10-09 17:31:31.790 4
14          3           1006        2011-10-01 00:00:00.000 2

(3 row(s) affected)
customer purchases/books a product and the same gets recorded into the BOOKING table now to generate the bill on his name we can uses a VIEW which would help us do away with a physical table. Instead it would enable us to generate the bill based on the information from these 3 tables itself. Let’s see how it’s possible.
CREATE VIEW Bill_V
AS
SELECT C.FName
      ,C.LNme
      ,P.ProductDesc
      ,B.DateOfBooking
      ,P.Price
      ,B.QTY
      ,(B.QTY*P.Price) AS TotalAmountPayable
FROM BOOKING B
INNER JOIN PRODUCTS P
ON B.ProductID=P.ProductID
INNER JOIN Customer C
ON B.CustID=C.CustID;
Next if I,
Select * from Bill_V
FName     LNme   ProductDesc DateOfBooking         Price   QTY     TotalAmountPayable
-------------------------------------------------- ------------------------------------
Sara      Verma  Biscuits   2011-11-01 00:00:00.000 20.00  3       60.00
Rick      Singh  Butter     2011-10-09 17:31:31.790 30.00  4       120.00
Micky     Khera  Milk       2011-10-01 00:00:00.000 46.00  2       92.00

(3 row(s) affected)
We have been able to generate the bill based on the 3 tables hence we have not only optimized the bill generation also we have saved ourselves from hosting a physical table in the database with this information.
  • This is the most credible use of a VIEW; it can not only reduce apparent complexity but also prevent redundant hosting of data in the DB.Next say there is some API which enables the Customer care executives to view the customerinformation details. Now exposing the Password might be risky, it’s strictly confidential info.
    We create a View which can be exposed to the API:
    CREATE VIEW dbo.CustomerInfo_V
    AS
    Select CustID
          ,FNAME AS [FIRST NAME]
          ,LNME AS [LAST NAME]
          ,UserID
    FROM dbo.Customer
    We have a created a View which can be used by the API to fetch customer details –(Minus) the Password Column.
  • Views can be used to prevent sensitive information from being selected, while still allowing other important data.Views do not have a physical existence, but still they do return a set of record set as a table does, the differences is it is simply an additional layer which calls the underlying code which finally returns the record set.



Sunday, November 18, 2012

How to start in Stock Markets?



Would you like to become a business owner without ever having to show up at work? I am sure all of you would. I am not talking about you getting a windfall gain through dowry; I am talking about you holding shares of a listed company on stock markets.
You must be wondering what this stock marketis? No, it is not a place where you sell goods, it is a place where securities (like shares and bonds) are bought and sold. ‘Share’ means a share in share capital of the company. In simple terms, if you buy some shares of a company you get part ownership of that company. Sounds good? Yes, it is very simple – but there is always risk involved in it. Why do I say it is risky? The value of a share can go down for several known and unknown reasons.
So how does one go about buying shares? How can I become a successful investor like Warren Buffet? FYI – Warren Buffet is widely regarded as one of the most successful investor in the world. Before you buy shares, you should know where and how you can buy them.
Step 1:  First open a Trading and Demat account with a registered broker. I don’t understand what this Trading Account or Demat Account mean, can you elaborate? ‘Trading Account’ – Just like you need a bank account to debit and creditcash, you need a trading account to buy and sell shares ‘Demat Account’ refers to dematerialized account which holds all your share certificates in electronic form rather than paper. How would you do that?
Simple, go to Google and search for registered brokerage houses in India you will find so many companies like HDFC, ICICI, SBI etc. Go to any brokerage house website you want to open your account with and call the toll free numberavailable on the website – within few minutes a representative from that company will fly into your house to give all necessary details of opening a new account.
Step 2: After collecting information of two or three brokerage firms you might decide to open an account with one who charges less brokerage charge and gives you good customer caresupport. What is a brokerage charge? When you buy or sell shares you will have to pay .5% or even less charge for that transaction. What other expenses do I incur when I buy/sell shares? You pay service tax and some other taxes for that transaction. How will I know about these charges? You will receive a report onto your email the same day or the next day of yourtrade.
Step 3: After having decided to open a Tradingand Demat account. You should mentally prepare yourself to sign several pages of application formAh! Once you are done you need to wait for few more days to get your account activated. Yuppie! You’re done with registration and activation. What next? You need to put some money intoyour account. How much?
Start Small – Don’t put all your money initially. First, learn about yourself and the market. What kind of player are you? Are you an Investor or a Trader or a Gambler? Gamblers are those who treat market as casino and play with it - never become a gambler unless you are a rich guy and you just want spend..spend..and only spend.Trader is an opportunist, who takes advantage of mispricing and makes profit from excessive greed and fear. An Investor is one who is optimistic, who has a long term view, who is ‘buy and hold’ types – who does lot of fundamental analysis of the company and buys shares which he thinks would do well in future.
Don’t get excited and jump without thinking – start learning about stock markets. What is NIFTY? What is SENSEX? How to analyze a company? How to select a good company in the current scenario? Read articles, books on fundamental analysis like ‘Warren Buffet way’ by Robert Hagstorm.
Now I know the basics of stock markets, what next? Observe the market. How it is behaving? Why is it going up/down? What do so called experts on the news channel say? You may wonder “how long should I observe the market?” The answer is “till you become completely familiar and confident about your decision to buy some company stocks/shares”. Try to get details about Price-Equity Ratio (P/E Ratio), Market Cap, Volumes etc of the company you are interested in -understand the business model. Shortlist one good stock which you think would do well in future and can give you above average returns – Invest in small quantities.
Don’t relax - keep tracking the company you have invested in; have a target price in mind; sell shares when you reach the target. Always good to be prepared for uncertainty, isn’t it? Have max fall of the share from your buying price you can afford to lose in mind; if the price of the share falls below that value; sell them by booking loss.
Practice and have a strategy that gives you good returns and learn from your mistakes.
Remember, stock markets are not a place to become rich overnight. Only few people are successful in this profession.

Top 10 Facebook facts ahead of its IPO


Top 10 Facebook facts ahead of its IPO


fb-sue.jpg

1) Facebook has more than 900 million active users. If the company were a country, it would be the third largest in the world after China (population: 1.34 billion) and India (population: 1.17 billion).

2) With 157 million members, the United States has the most Facebook users, followed by India with 45.9 million, Brazil with 45.3 million, Indonesia with 42.4 million and Mexico with 32.9 million. (source: socialbakers.com)

3) Facebook is the most popular social network in every country of the world, with the exceptions of China, Japan, Russia, South Korea and Vietnam. (source: comScore)

4) In April, Facebook announced a billion-dollar deal to buy the startup behind wildly popular smartphone photo sharing application Instagram, its biggest acquisition to date.

5) Facebook has minted four billionaires: Mark Zuckerberg, Dustin Moskovitz, Eduardo Saverin and Sean Parker. The 27-year-old Zuckerberg's net worth was estimated at $17.5 billion on the 2011 Forbes list of the wealthiest Americans. Moskovitz had a net worth of $3.5 billion but pipped Zuckerberg for the title of world's youngest billionaire, being eight days younger. The Brazilian-born Saverin, who left Facebook early on after a falling-out with Zuckerberg, had a net worth of $2 billion. Parker, the Napster co-founder who briefly served as Facebook's president, had a net worth of $2.1 billion.

6) Chris Hughes, one of Facebook's four co-founders, served as director of online organizing for Barack Obama's successful 2008 presidential campaign.

7) Facebook says it had an average of 526 million daily active users in March 2012, an increase of 41 percent from a year ago. It had registered 125 billion "friend connections" as of March 31 and 3.2 billion "likes" and comments.

8) More than 300 million photos are uploaded to Facebook every day and more than 488 million active users access Facebook using mobile devices.

9) "The Social Network," the 2010 film about the origins of Facebook, won four Golden Globes -- including for best picture and best director -- but flopped at the Oscars, walking away with only awards for best adapted screenplay, original score and film editing.

10) Facebook, which currently employs some 3,500 people, has announced plans to hire "thousands" more over the next year.