Friday, 15 July 2011

Server Environment Server Environment Functions

  • SELECT GETDATE()

  • SELECT GETDATE() AS 'Date',DB_NAME() AS 'Database'

  • SELECT @@SERVERNAME 

  • SELECT   SERVERPROPERTY ('ServerName') AS ServerName,SERVERPROPERTY ('Edition') AS Edition, SERVERPROPERTY ('EngineEdition') AS EngineEdition, SERVERPROPERTY ('ProductLevel') AS ProductLevel

-- User Information Functions
  • SELECT   USER_NAME() AS 'User',  SUSER_SNAME() AS 'Login',  HOST_NAME() AS 'Workstation',  APP_NAME() AS 'Application'

---Date/Time Functions

  • SELECT DATENAME(YEAR, GETDATE()) AS YEAR

  • UPDATE Guide   SET DateOfBirth = '9/4/58'  WHERE lastName = 'Frank'

  • SELECT LastName,  DATENAME(yy,DateOfBirth) AS [Year],   DATENAME(mm,DateOfBirth) AS [Month],    DATENAME(dd,DateOfBirth) AS [Day],   DATENAME(WEEKDAY, DateOfBirth) AS BirthDay  FROM Guide  WHERE DateOfBirth IS NOT NULL

  • SELECT DATEPART(DayofYear, GETDATE()) AS DayCount
  • SELECT DATEPART(dw, GETDATE()) AS DayWeek

-- Date Math

  • SELECT DATEDIFF(yy,'2005/10/22', GETDATE()) AS MarriedYears,  DATEDIFF(dd,'2005/10/22', GETDATE()) AS MarriedDays

  • SELECT DATEADD(hh,100, GETDATE()) AS [100HoursFromNow]
  •  SELECT DATEDIFF(dd,getdate(),dateadd(yy,10,getdate()))

Dealing with null( is null) (is not null) and COALESCE

SELECT CASE
  WHEN Null = NULL THEN 'True'
  ELSE 'False'
  END as '=null'

SELECT CASE
  WHEN Null IS NULL THEN 'True'
  ELSE 'False'
  END as ' IS null'

SELECT FirstName, LastName, Nickname  FROM Customer  WHERE NickName IS NOT NULL ORDER BY LastName, FirstName


select COALESCE(customersince, companyname) from  OBXKites.dbo.Contact where contactcode=106

Case Statement

 /*
CASE
  WHEN BooleanCondition THEN Expression
  WHEN BooleanCondition THEN Expression
    ...
  ELSE Expression
END AS Alias
 */

SELECT CustomerTypeName, [Default],
    CASE [Default]
      WHEN 1 THEN 'default type'
      WHEN 0 THEN 'alternate'
      ELSE '-'
    End as AssignStatus
  From dbo.CustomerType

Where Clause

/*
SELECT *
  FROM data source(s)
  WHERE condition
*/

-- a boolean condition
SELECT *  FROM dbo.Tour  WHERE 1 = 1;

-- Comparison Operator
SELECT *  FROM dbo.Tour  WHERE TourID <= 3;

-- Between
SELECT *  FROM dbo.Tour  WHERE TourID BETWEEN 2 AND 4;

SELECT *  FROM dbo.Tour  WHERE TourID >= 2    AND TourID <= 4;

-- In Condition
SELECT *  FROM dbo.Tour  WHERE TourID IN (1, 3);

UPDATE dbo.BaseCamp SET Region = 'NC' WHERE Name = 'Ashville';
UPDATE dbo.BaseCamp SET Region = 'NC' WHERE Name = 'Cape Hatteras';
UPDATE dbo.BaseCamp SET Region = 'BA' WHERE Name = 'Freeport';
UPDATE dbo.BaseCamp SET Region = 'FL' WHERE Name = 'Ft Lauderdale';
UPDATE dbo.BaseCamp SET Region = 'WV' WHERE Name = 'West Virginia';

SELECT *  FROM dbo.BaseCamp  WHERE Region IN ('NC', 'WV');

-- Like Condition
/*
multiple characters    %
single character        _
match in range        [ ]
match not in range    [^ ]
*/

SELECT *  FROM dbo.BaseCamp  WHERE Name LIKE 'F%';

SELECT *  FROM dbo.Customer  WHERE LastName LIKE '%son';

SELECT *  FROM dbo.Customer  WHERE FirstName LIKE '[ABC]%';

SELECT *  FROM dbo.Customer  WHERE FirstName LIKE '[^ABC]%';

-- Multiple Conditions
SELECT *  FROM dbo.Customer  WHERE   CustomerTypeID = 1     OR        FirstName LIKE  'Dav%'     AND        CustomerID = 14;

SELECT *  FROM dbo.Customer  WHERE       (CustomerTypeID = 1         OR        FirstName LIKE 'Dav%')      AND        CustomerID = 14;

Simple SQL statement

 /*
SELECT *
  FROM
    tables(s)
    subqueries (as derived tables) AS NamedRangeAlias
    common table expressions (CTE)
    views
    table-valued user-defined functions
    distributed data sources (OpenQuery) 
    XML data sources (XQuery)
*/

SELECT 'SQL Rocks';

SELECT *   FROM Tour;

-- Fully Qualified - Four Part Name

-- SELECT * --   FROM Server.Database.Schema.Object;

SELECT *   FROM dbo.Tour;
SELECT *   FROM dbo.Tour;

varchar and nvarchar

  • nvarchar stores unicode data while varchar stores ascii data. They function identically but nvarchar takes up twice as much space.


An nvarchar column can store any Unicode data. A varchar column is restricted to an 8-bit codepage. Some people think that varchar should be used because it takes up less space. I believe this is not the correct answer. Codepage incompatabilities are a pain, and Unicode is the cure for codepage problems. With cheap disk and memory nowadays, there is really no reason to waste time mucking around with code pages anymore.
All modern operating systems and development platforms use Unicode internally. By using nvarchar rather than varchar, you can avoid doing encoding conversions every time you read from or write to the database. Conversions take time, and are prone to errors. And recovery from conversion errors is a non-trivial problem.
If you are interfacing with an application that uses only ASCII, I would still recommend using Unicode in the database. The OS and database collation algorithms will work better with Unicode. Unicode avoids conversion problems when interfacing with other systems. And you will be preparing for the future. And you can always validate that your data is restricted to 7-bit ASCII for whatever legacy system you're having to maintain, even while enjoying some of the benifits of full Unicode storage.

Wednesday, 13 July 2011

Basic

Toggle Result Pane - ctrl + R
-- Switch Default Database
                                       USE databasename;

-- Statement Terminator   ;
-- Batch Terminator        GO

-- Fully Qualified - Four Part Name
                                                   Server.Database.Schema.Object

Managing Optional Data

  1. Missing rows: poor performance hard to manage(super type sub type relationship)
  2. Null-able Columns: Efficient
  3. Surrogate nulls: In-consistence

Patterns in a database

  • One to many:   use of foreign key
  • Many to Many: Mapping table
  • Super-type subtype Relationship:Generalization
  • Reflexive pattern(hierarchy pattern):Self join type pattern

Constraints on Database Items

You can place constraints to limit the type of data that can go into a table. Such constraints can be specified when the table when the table is first created via the CREATE TABLE statement, or after the table is already created via the ALTER TABLE statement.
Common types of constraints include the following:

Check Constraints

A check constraint is the most generic constraint type. It allows you to specify that the value in a certain column must satisfy an arbitrary expression. For instance, to require positive product prices, you could use:


CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CHECK (price > 0)
);
 

As you see, the constraint definition comes after the data type, just like default value definitions. Default values and constraints can be listed in any order. A check constraint consists of the key word CHECK followed by an expression in parentheses. The check constraint expression should involve the column thus constrained, otherwise the constraint would not make too much sense.

You can also give the constraint a separate name. This clarifies error messages and allows you to refer to the constraint when you need to change it. The syntax is:

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CONSTRAINT positive_price CHECK (price > 0)
);
So, to specify a named constraint, use the key word CONSTRAINT followed by an identifier followed by the constraint definition.
A check constraint can also refer to several columns. Say you store a regular price and a discounted price, and you want to ensure that the discounted price is lower than the regular price.
CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CHECK (price > 0),
    discounted_price numeric CHECK (discounted_price > 0),
    CHECK (price > discounted_price)
);
 

The first two constraints should look familiar. The third one uses a new syntax. It is not attached to a particular column, instead it appears as a separate item in the comma-separated column list. Column definitions and these constraint definitions can be listed in mixed order.

We say that the first two constraints are column constraints, whereas the third one is a table constraint because it is written separately from the column definitions. Column constraints can also be written as table constraints, while the reverse is not necessarily possible. The above example could also be written as

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric,
    CHECK (price > 0),
    discounted_price numeric,
    CHECK (discounted_price > 0),
    CHECK (price > discounted_price)
);
 
or even

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CHECK (price > 0),
    discounted_price numeric,
    CHECK (discounted_price > 0 AND price > discounted_price)
);
 
It's a matter of taste.

 not-null constraint
A not-null constraint simply specifies that a column must not assume the null value. A syntax example:
CREATE TABLE products (
    product_no integer NOT NULL,
    name text NOT NULL,
    price numeric
);
 

A not-null constraint is always written as a column constraint. A not-null constraint is functionally equivalent to creating a check constraint CHECK (column_name IS NOT NULL), but in PostgreSQL creating an explicit not-null constraint is more efficient. The drawback is that you cannot give explicit names to not-null constraints created that way.

Of course, a column can have more than one constraint. Just write the constraints after one another:
CREATE TABLE products (
    product_no integer NOT NULL,
    name text NOT NULL,
    price numeric NOT NULL CHECK (price > 0)
);
The order doesn't matter. It does not necessarily affect in which order the constraints are checked.
The NOT NULL constraint has an inverse: the NULL constraint. This does not mean that the column must be null, which would surely be useless. Instead, this simply defines the default behavior that the column may be null. The NULL constraint is not defined in the SQL standard and should not be used in portable applications. (It was only added to PostgreSQL to be compatible with other database systems.) Some users, however, like it because it makes it easy to toggle the constraint in a script file. For example, you could start with

CREATE TABLE products (
    product_no integer NULL,
    name text NULL,
    price numeric NULL
);
and then insert the NOT key word where desired.



Unique Constraints

Unique constraints ensure that the data contained in a column or a group of columns is unique with respect to all the rows in the table. The syntax is

CREATE TABLE products (
    product_no integer UNIQUE,
    name text,
    price numeric
);
when written as a column constraint, and
 
CREATE TABLE products (
    product_no integer,
    name text,
    price numeric,
    UNIQUE (product_no)
);
when written as a table constraint.
If a unique constraint refers to a group of columns, the columns are listed separated by commas:
 
CREATE TABLE example (
    a integer,
    b integer,
    c integer,
    UNIQUE (a, c)
);

It is also possible to assign names to unique constraints:
 
CREATE TABLE products (
    product_no integer CONSTRAINT must_be_different UNIQUE,
    name text,
    price numeric
);
 
 

In general, a unique constraint is violated when there are (at least) two rows in the table where the values of each of the corresponding columns that are part of the constraint are equal. However, null values are not considered equal in this consideration. That means, in the presence of a multicolumn unique constraint it is possible to store an unlimited number of rows that contain a null value in at least one of the constrained columns. This behavior conforms to the SQL standard, but we have heard that other SQL databases may not follow this rule. So be careful when developing applications that are intended to be portable.


Primary Keys

Technically, a primary key constraint is simply a combination of a unique constraint and a not-null constraint. So, the following two table definitions accept the same data:

CREATE TABLE products (
    product_no integer UNIQUE NOT NULL,
    name text,
    price numeric
);
 

CREATE TABLE products (
    product_no integer PRIMARY KEY,
    name text,
    price numeric
);

Primary keys can also constrain more than one column; the syntax is similar to unique constraints:
 
CREATE TABLE example (
    a integer,
    b integer,
    c integer,
    PRIMARY KEY (a, c)
);
 

A primary key indicates that a column or group of columns can be used as a unique identifier for rows in the table. (This is a direct consequence of the definition of a primary key. Note that a unique constraint does not, in fact, provide a unique identifier because it does not exclude null values.) This is useful both for documentation purposes and for client applications. For example, a GUI application that allows modifying row values probably needs to know the primary key of a table to be able to identify rows uniquely.
A table can have at most one primary key (while it can have many unique and not-null constraints). Relational database theory dictates that every table must have a primary key. This rule is not enforced by PostgreSQL, but it is usually best to follow it.

Foreign Keys

A foreign key constraint specifies that the values in a column (or a group of columns) must match the values appearing in some row of another table. We say this maintains the referential integrity between two related tables.
Say you have the product table that we have used several times already:

CREATE TABLE products (
    product_no integer PRIMARY KEY,
    name text,
    price numeric
);
 
Let's also assume you have a table storing orders of those products. We want to ensure that the orders table only contains orders of products that actually exist. So we define a foreign key constraint in the orders table that references the products table:
 
CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    product_no integer REFERENCES products (product_no),
    quantity integer
);
 
Now it is impossible to create orders with product_no entries that do not appear in the products table.


Normalization :The Rule of One

What is Normalization?

Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process: eliminating redundant data (for example, storing the same data in more than one table) and ensuring data dependencies make sense (only storing related data in a table). Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.

The Normal Forms

The database community has developed a series of guidelines for ensuring that databases are normalized. These are referred to as normal forms and are numbered from one (the lowest form of normalization, referred to as first normal form or 1NF) through five (fifth normal form or 5NF). In practical applications, you'll often see 1NF, 2NF, and 3NF along with the occasional 4NF. Fifth normal form is very rarely seen


First Normal Form (1NF)

First normal form (1NF) sets the very basic rules for an organized database:
  • Eliminate duplicate columns from the same table.
  • Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).
  •  What will you do to store multiple phone number for a person....???

Second Normal Form (2NF)

Second normal form (2NF) further addresses the concept of removing duplicate data:
  • Meet all the requirements of the first normal form.
  • Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
  • Create relationships between these new tables and their predecessors through the use of foreign keys.


Third normal form (3NF) goes one large step further:
  • Meet all the requirements of the second normal form.
  • Remove columns that are not dependent upon the primary key.


Boyce-Codd Normal Form (BCNF or 3.5NF)

The Boyce-Codd Normal Form, also referred to as the "third and half (3.5) normal form", adds one more requirement:
  • Meet all the requirements of the third normal form.
  • Every determinant must be a candidate key.
 A candidate key is a combination of attributes that can be uniquely used to identify a database record without any extraneous data. Each table may have one or more candidate keys. One of these candidate keys is selected as the table primary key.

Fourth Normal Form (4NF)

Finally, fourth normal form (4NF) has one additional requirement:
  • Meet all the requirements of the third normal form.
  • A relation is in 4NF if it has no multi-valued dependencies.
Multivalued dependencies occur when the presence of one or more rows in a table implies the presence of one or more other rows in that same table.

Examples:
For example, imagine a car company that manufactures many models of car, but always makes both red and blue colors of each model. If you have a table that contains the model name, color and year of each car the company manufactures, there is a multivalued dependency in that table. If there is a row for a certain model name and year in blue, there must also be a similar row corresponding to the red version of that same car.

 Normalization: The first three forms


First Normal Form:
No repeating groups. As an example, it might be tempting to make an invoice table with columns for the first, second, and third line item (see above). This violates the first normal form, and would result in large rows, wasted space (where an invoice had less than the maximum number of line items), and *horrible* SQL statements with a separate join for each repetition of the column. First form normalization requires you make a separate line item table, with it's own key (in this case the combination of invoice number and line number) (See below).
Second Normal Form:
Each column must depend on the *entire* primary key. As an example, the customer information could be put in the line item table (see above). The trouble with that is that the customer goes with the invoice, not with each line on the invoice. Putting customer information in the line item table will cause redundant data, with it's inherant overhead and difficult modifications. Second form normalization requires you place the customer information in the invoice table (see below).

Third Normal Form:
Each column must depend on *directly* on the primary key. As an example, the customer address could go in the invoice table (see above), but this would cause data redundancy if several invoices were for the same customer. It would also cause an update nightmare when the customer changes his address, and would require extensive programming to insert the address every time an existing customer gets a new invoice. Third form normalization requires the customer address go in a separate customer table with its own key (customer), with only the customer identifier in the invoice table (see below).



 The rule of one.....

One type of Item = one table(one Entity)
One Item = one tuple (row)
One Descriptive fact(attribute)=One column
Every attribute must describe the entity

Should I Normalize My Database?

The bottom line is that you should normalize your databases unless you have a really good reason not to do so. Normalizing is usually sound design practice. It reduces redundant information, which optimizes performance and reduces the likelihood that you’ll have data integrity issues that result from having the same data stashed in different corners of your database.

Some Good Reasons Not To Normalize
That said, there are some good reasons not to normalize your database. Let’s look at a few:


Joins are expensive. Normalizing your database often involves creating lots of tables. In fact, you can easily wind up with what might seem like a simple query spanning five or ten tables. If you’ve ever tried doing a five-table join, you know that it works in principle, but its painstakingly slow in practice. If you’re building a web application that relies upon multiple-join queries against large tables, you might find yourself thinking: “If only this database wasn’t normalized!” When you hear that thought in your head, it’s a good time to consider denormalizing. If you can stick all of the data used by that query into a single table without really jeopardizing your data integrity, go for it! Be a rebel and denormalize your database. You won’t look back!

Normalized design is difficult. If you’re working with a complex database schema, you’ll probably find yourself banging your head against the table over the complexity of normalization. As a simple rule of thumb, if you’ve been banging your head against the table for an hour or two trying to figure out how to move to the fourth normal form, you might be taking normalization too far. Step back and ask yourself if it’s really worth continuing.

Quick and dirty should be quick and dirty. If you’re just developing a prototype, just do whatever works quickly. Really. It’s OK. Rapid application development is sometimes more important than elegant design. Just remember to go back and take a careful look at your design once you’re ready to move beyond the prototyping phase. The price you pay for a quick and dirty database design is that you might need to throw it away and start over when it’s time to build for production.

As I mentioned up front, database normalization is generally a good idea. You should try to follow the principles of normalization when it seems reasonable to do so. My point here is that you shouldn’t let a quasi-religious fanaticism about normalization prevent you from doing your job in the best way possible.

As a parting thought, I offer some words of caution. When you do choose to vary from the rules of normalization, you’ll need to be extra vigilant about the way you enforce database integrity. If you store redundant information, put triggers and other controls in place to make sure that information stays consistent.