Wednesday, January 27, 2010

FOREIGN KEY


Share/Save/Bookmark
A foreign key (FK) is a column or combination of columns that is used to establish and enforce a link between the data in two tables. You can create a foreign key by defining a FOREIGN KEY constraint when you create or modify a table.
In a foreign key reference, a link is created between two tables when the column or columns that hold the primary key value for one table are referenced by the column or columns in another table. This column becomes a foreign key in the second table.
For example, the Sales.SalesOrderHeader table in the AdventureWorks database has a link to the Sales.SalesPerson table because there is a logical relationship between sales orders and salespeople. The SalesPersonID column in the SalesOrderHeader table matches the primary key column of the SalesPerson table. The SalesPersonID column in the SalesOrderHeader table is the foreign key to the SalesPerson table.
SalesOrderHeader.SalesPersonID is a foreign key.
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table. A FOREIGN KEY constraint can contain null values; however, if any column of a composite FOREIGN KEY constraint contains null values, verification of all values that make up the FOREIGN KEY constraint is skipped. To make sure that all values of a composite FOREIGN KEY constraint are verified, specify NOT NULL on all the participating columns.

from : technet.microsoft.com

CHECK CONSTRAINT


Share/Save/Bookmark
A check constraint (also known as table check constraint) is a condition that defines valid data when adding or updating an entry in a table of a relational database. A check constraint is applied to each row in the table. The constraint must be a predicate. It can refer to a single or multiple columns of the table. The result of the predicate can be either TRUE, FALSE, or UNKNOWN, depending on the presence of NULLs. If the predicate evaluates to UNKNOWN, then the constraint is not violated and the row can be inserted or updated in the table. This is contrary to predicates in WHERE clauses in SELECT or UPDATE statements.
For example, in a table containing products, one could add a check constraint such that the price of a product and quantity of a product is a non-negative value:
PRICE >= 0
QUANTITY >= 0
If these constraints were not in place, it would be possible to have a negative price (-$30) or quantity (-3 items).
Check constraints are used to ensure the validity of data in a database and to provide data integrity. If they are used at the database level, applications that use the database will not be able to add invalid data or modify valid data so the data becomes invalid, even if the application itself accepts invalid data.

Definition

Each check constraint has to be defined in the CREATE TABLE or ALTER TABLE statement using the syntax:
CREATE TABLE table_name (
    ...,
    CONSTRAINT constraint_name CHECK ( predicate ),
    ...
 )
ALTER TABLE table_name
    ADD CONSTRAINT constraint_name CHECK ( predicate )
If the check constraint refers to a single column only, it is possible to specify the constraint as part of the column definition.
CREATE TABLE table_name (
    ...
    column_name type CHECK ( predicate ),
    ...
 )

NOT NULL Constraint

A NOT NULL constraint is functionally equivalent to the following check constraint with an IS NOT NULL predicate:
CHECK (column IS NOT NULL)
Some relational database management systems are able to optimize performance when the NOT NULL constraint syntax is used as opposed to the CHECK constraint syntax given above.

 Common Restrictions

Most database management systems restrict check constraints to a single row, with access to constants and deterministic functions, but not to data in other tables, or to data invisible to the current transaction because of transaction isolation.
Such constraints are not truly table check constraints but rather row check constraints. Because these constraints are generally only verified when a row is directly updated (for performance reasons,) and often implemented as implied INSERT or UPDATE triggers, integrity constraints could be violated by indirect action were it not for these limitations. Future, otherwise-valid modifications to these records would then be prevented by the CHECK constraint. Some examples of dangerous constraints include:
  • CHECK ((select count(*) from invoices where invoices.customerId = customerId) < 1000)
  • CHECK (dateInserted = CURRENT_DATE)
  • CHECK (countItems = RAND())
User-defined triggers can be used to work around these restrictions. Although similar in implementation, it is semantically clear that triggers will only be fired when the table is directly modified, and that it is the designer's responsibility to handle indirect, important changes in other tables; constraints on the other hand are intended to be "true at all times" regardless of the user's actions or the designer's lack of foresight.

from : wikipedia.org

UNIQUE CONTRAINTS


Share/Save/Bookmark

What is a unique constraint?

A unique constraint is a single field or combination of fields that uniquely defines a record. Some of the fields can contain null values as long as the combination of values is unique.
Note:
In Oracle, a unique constraint can not contain more than 32 columns.
A unique constraint can be defined in either a CREATE TABLE statement or an ALTER TABLE statement.

What is the difference between a unique constraint and a primary key?

Primary Key
Unique Constraint
None of the fields that are part of the primary key can contain a null value.
Some of the fields that are part of the unique constraint can contain null values as long as the combination of values is unique.
Oracle does not permit you to create both a primary key and unique constraint with the same columns.

Using a CREATE TABLE statement

The syntax for creating a unique constraint using a CREATE TABLE statement is:
CREATE TABLE table_name
(column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT constraint_name UNIQUE (column1, column2, . column_n)
);

For example:
CREATE TABLE supplier
(
supplier_id
numeric(10)
not null,

supplier_name
varchar2(50)
not null,

contact_name
varchar2(50),


CONSTRAINT supplier_unique UNIQUE (supplier_id)
);
In this example, we've created a unique constraint on the supplier table called supplier_unique. It consists of only one field - the supplier_id field.

We could also create a unique constraint with more than one field as in the example below:
CREATE TABLE supplier
(
supplier_id
numeric(10)
not null,

supplier_name
varchar2(50)
not null,

contact_name
varchar2(50),


CONSTRAINT supplier_unique UNIQUE (supplier_id, supplier_name)
);

Using an ALTER TABLE statement

The syntax for creating a unique constraint in an ALTER TABLE statement is:
ALTER TABLE table_name
add CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n);

For example:
ALTER TABLE supplier
add CONSTRAINT supplier_unique UNIQUE (supplier_id);
In this example, we've created a unique constraint on the existing supplier table called supplier_unique. It consists of the field called supplier_id.

We could also create a unique constraint with more than one field as in the example below:
ALTER TABLE supplier
add CONSTRAINT supplier_unique UNIQUE (supplier_id, supplier_name);

Drop a Unique Constraint

The syntax for dropping a unique constraint is:
ALTER TABLE table_name
drop CONSTRAINT constraint_name;

For example:
ALTER TABLE supplier
drop CONSTRAINT supplier_unique;
In this example, we're dropping a unique constraint on the supplier table called supplier_unique.

Disable a Unique Constraint

The syntax for disabling a unique constraint is:
ALTER TABLE table_name
disable CONSTRAINT constraint_name;

For example:
ALTER TABLE supplier
disable CONSTRAINT supplier_unique;
In this example, we're disabling a unique constraint on the supplier table called supplier_unique.

Enable a Unique Constraint

The syntax for enabling a unique constraint is:
ALTER TABLE table_name
enable CONSTRAINT constraint_name;

For example:
ALTER TABLE supplier
enable CONSTRAINT supplier_unique;
In this example, we're enabling a unique constraint on the supplier table called supplier_unique.


from : www.techonthenet.com

PRIMARY KEY


Share/Save/Bookmark

PRIMARY KEY Constraints

A table usually has a column or combination of columns whose values uniquely identify each row in the table. This column (or columns) is called the primary key of the table and enforces the entity integrity of the table. You can create a primary key by defining a PRIMARY KEY constraint when you create or alter a table.
A table can have only one PRIMARY KEY constraint, and a column that participates in the PRIMARY KEY constraint cannot accept null values. Because PRIMARY KEY constraints ensure unique data, they are often defined for identity column.
When you specify a PRIMARY KEY constraint for a table, Microsoft® SQL Server™ 2000 enforces data uniqueness by creating an unique index, for the primary key columns. This index also permits fast access to data when the primary key is used in queries.
If a PRIMARY KEY constraint is defined on more than one column, values may be duplicated within one column, but each combination of values from all the columns in the PRIMARY KEY constraint definition must be unique.
As shown in the following illustration, the au_id and title_id columns in the titleauthor table form a composite PRIMARY KEY constraint for the titleauthor table, which ensures that the combination of au_id and title_id is unique.

When you work with joins, PRIMARY KEY constraints relate one table to another. For example, to determine which authors have written which books, you can use a three-way join between the authors table, the titles table, and the titleauthor table. Because titleauthor contains columns for both the au_id and title_id columns, the titles table can be accessed by the relationship between titleauthor and titles.
from : msdn.microsoft.com

CONSTRAINT


Share/Save/Bookmark
In the object hierarchy under any table, you will find Constraints. Constraints can be added by selecting ADD TABLE CONSTRAINT from the Constraints context menu. Once a constraint has been created, it can also be commented on and dropped. This section describes how to create, comment on, and drop a constraint with RHDB Administrator.
Constraints are not actual entities themselves (except for check constraints). Constraints are mostly a collection of indexes and triggers that restrict certain actions on a table. There are four types of constraints:
Primary Key Constraints
Unique Constraints
Check Constraints
Foreign Key (FK) Constraints.
The following sections describe each of these constraints in brief and provide an example of how to create them. Note that all of these examples are based on the table invoices

Primary Key Constraints

A primary key is a type of index that will most likely be used as the primary index when a query is made on the table (assuming of course, that one of the conditional fields in the query pertains to the column on which the index exists).

Unique Constraints

Unique constraints may be placed on multiple columns. They constrain the UPDATE/INSERTS on the table so that the values being updated or inserted do not match any other row in the table for the corresponding values.

Check Constraints

A check constraint prevents updates/inserts on the table by placing a check condition on the selected column. The UPDATE/INSERT is allowed only if the check condition qualifies.

Foreign Key (FK) Constraints

A foreign key constraint allows certain fields in one table to refer to fields in another table. This type of constraint is useful if you have two tables, one of which has partial information, details on which can be sought from another table with a matching entry. A foreign key constraint in this case will prevent the deletion of an entry from the table with detailed information if there is an entry in the table with partial information that matches it.

from : www.redhat.com

RELATIONAL DATABASE


Share/Save/Bookmark
A relational database matches data by using common characteristics found within the data set. The resulting groups of data are organized and are much easier for people to understand.
For example, a data set containing all the real-estate transactions in a town can be grouped by the year the transaction occurred; or it can be grouped by the sale price of the transaction; or it can be grouped by the buyer's last name; and so on.
Such a grouping uses the relational model (a technical term for this is schema). Hence, such a database is called a "relational database."
The software used to do this grouping is called a relational database management system. The term "relational database" often refers to this type of software.
Relational databases are currently the predominant choice in storing financial records, manufacturing and logistical information, personnel data and much more.

 Contents
Strictly, a relational database is a collection of relations (frequently called tables). Other items are frequently considered part of the database, as they help to organize and structure the data, in addition to forcing the database to conform to a set of requirements.

Terminology

The term relational database was originally defined and coined by Edgar Codd at IBM Almaden Research Center in 1970.[1]


Relational database terminology.
Relational database theory uses a set of mathematical terms, which are roughly equivalent to SQL database terminology. The table below summarizes some of the most important relational database terms and their SQL database equivalents.

Relational term
SQL equivalent
relation, base relvar  
table
derived relvar
view, query result, result set
tuple
row
attribute
column

Relations or Tables

A relation is defined as a set of tuples that have the same attributes. A tuple usually represents an object and information about that object. Objects are typically physical objects or concepts. A relation is usually described as a table, which is organized into rows and columns All the data referenced by an attribute are in the same domain and conform to the same constraints.
The relational model specifies that the tuples of a relation have no specific order and that the tuples, in turn, impose no order on the attributes. Applications access data by specifying queries, which use operations such as select to identify tuples, project to identify attributes, and join to combine relations. Relations can be modified using the insert, delete, and update operators. New tuples can supply explicit values or be derived from a query. Similarly, queries identify tuples for updating or deleting. It is necessary for each tuple of a relation to be uniquely identifiable by some combination (one or more) of its attribute values. This combination is referred to as the primary key.


from : wikipedia

QUERY


Share/Save/Bookmark
Query languages are computer language used to make queries into databases and information system
Broadly, query languages can be classified according to whether they are database Query languages or information retrieval query language Examples include:

STORE PROCEDURE


Share/Save/Bookmark
A stored procedure is subroutine available to applications accessing a relational  database system Stored procedures (sometimes called a proc, sproc, StoPro, or SP) are actually stored in the database data dictionary..
Typical uses for stored procedures include data validation (integrated into the database) or acces control mechanisms. Furthermore, stored procedures are used to consolidate and centralize logic that was originally implemented in applications. Large or complex processing that might require the execution of several SQL statements is moved into stored procedures, and all applications call the procedures only.
Stored procedures are similar to UDFs. The major difference is that UDFs can be used like any other expression within SQL statements, whereas stored procedures must be invoked using the CALL statement
CALL procedure(…)
or
EXECUTE procedure(…)
Stored procedures can return result set, i.e. the results of a SELECT statement. Such result sets can be processed using cursor by other stored procedures by associating a result set locator, or by applications. Stored procedures may also contain declared variables for processing data and cursors that allow it to loop through multiple rows in a table. The standard Structured Query Language provides IF, WHILE, LOOP, REPEAT, CASE statements, and more. Stored procedures can receive variables, return results or modify variables and return them, depending on how and where the variable is declared.
The exact and correct implementation of stored procedure varies from one database system to another. Most major database vendors support them in some form. Depending on the database system, stored procedures can be implemented in a variety of programming language, for example SQL, Java, C, or C++. Stored procedures written in non-SQL programming languages may or may not execute SQL statements themselves.
The increasing adoption of stored procedures led to the introduction of procedural elements to the SQL language in the SQL:1999 and SQL:2003 standards in the part SQL/PSM. That made SQL an imperative programming language. Most database systems offer proprietary and vendor-specific extensions, exceeding SQL/PSM.

 
Database System
Implementation Language
Microsoft SQL Server
Transact-SQL and various .NET Framework languages
Oracle
PL/SQL or Java
DB2
SQL/PL
Informix
SPL
PostgreSQL
PL/pgSQL, can also use own function languages such as pl/perl or pl/php
Firebird
PSQL (Fyracle also supports portions of Oracle's PL/SQL)
MySQL
own stored procedures, closely adhering to SQL:2003 standard.

 
from : wikipedia 

VIEW


Share/Save/Bookmark
In database theory, a view consists of a stored query accessible as a virtual table composed of the result set of a query. Unlike ordinary tables (base tables) in a relational database, a view does not form part of the physical schema: it is a dynamic, virtual table computed or collated from data in the database. Changing the data in a table alters the data shown in subsequent invocations of the view.
Views can provide advantages over tables:
  • Views can represent a subset of the data contained in a table
  • Views can join and simplify multiple tables into a single virtual table
  • Views can act as aggregated tables, where the database engine aggregates data (sum, average etc) and presents the calculated results as part of the data
  • Views can hide the complexity of data; for example a view could appear as Sales2000 or Sales2001, transparently partitioning the actual underlying table
  • Views take very little space to store; the database contains only the definition of a view, not a copy of all the data it presents
  • Depending on the SQL engine used, views can provide extra security
  • Views can limit the degree of exposure of a table or tables to the outer world
Just as functions (in programming) can provide abstraction, so database users can create abstraction by using views. In another parallel with functions, database users can manipulate nested views, thus one view can aggregate data from other views. Without the use of views the normalization of databases above  secind normal form would become much more difficult. Views can make it easier to create lossless join decomposition.
Just as rows in a base table lack any defined ordering, rows available through a view do not appear with any default sorting. A view is a relational table, and the relational model defines a table as a set of rows. Since sets are not ordered - by definition - the rows in a view are not ordered, either. Therefore, an order byclause in the view definition is meaningless. The SQL standard does not allow an ORDER BY clause in a subselect in a CREATE VIEW statement, just as it is not allowed in a CREATE TABLE statement. However, sorted data can be obtained from a view, in the same way as any other table - as part of a query statement. In Oracle 10g, a view can be created with an ORDER BY clause in a subquery.

TABLE


Share/Save/Bookmark
In relational database and flat files database,  a table is a set of data elements (values) that is organized using a model of vertical columns (which are identified by their name) and horizontal rows. A table has a specified number of columns, but can have any number of rows. Each row is identified by the values appearing in a particular column subset which has been identified as a candidate key. Table is another term for relations; although there is the difference in that a table is usually a multi-set (bag) of rows whereas a relation is a set and does not allow duplicates. Besides the actual data rows, tables generally have associated with them somemeta information, such as constraints on the table or on the values within particular columns.
The data in a table does not have to be physically stored in the database. Views are also relational tables, but their data are calculated at query time. Another example are nicknames, which represent a pointer to a table in another database.

from: wikipedia.com

TRIGGER


Share/Save/Bookmark
A database trigger is procedural code that is automatically executed in response to certain events on a particular table or view in a database. The trigger is mostly used for keeping the integrity of the information on the database. For example, when a new record (representing a new worker) added to the employees table, new records should be created also in the tables of the taxes, vacations, and salaries.

DML Triggers

There are typically three triggering events that cause data triggers to 'fire':
  • INSERT event (as a new record is being inserted into the database).
  • UPDATE event (as a record is being changed).
  • DELETE event (as a record is being deleted).
Structurally, triggers are either "row triggers" or "statement triggers". Row triggers define an action for every row of a table, while statement triggers occur only once per INSERT, UPDATE, or DELETE statement. DML triggers cannot be used to audit data retrieval via SELECT statements, because SELECT is not a triggering event.
Furthermore, there are "BEFORE triggers" and "AFTER triggers" which run in addition to any changes already being made to the database, and "INSTEAD OF trigger" which fully replace the database's normal activity.
Triggers do not accept parameters, but they do receive information in the form of implicit variables. For row-level triggers, these are generally OLD and NEW variables, each of which have fields corresponding to the columns of the affected table or view; for statement-level triggers, something like SQL Server's Inserted and Deleted tables may be provided so the trigger can see all the changes being made.
For data triggers, the general order of operations will be as follows:
  1. a statement requests changes on a row: OLD represents the row as it was before the change (or is all-null for inserted rows), NEW represents the row after the changes (or is all-null for deleted rows)
  2. each statement-level BEFORE trigger is fired
  3. each row-level BEFORE trigger fires, and can modify NEW (but not OLD); each trigger can see NEW as modified by its predecessor, they are chained together
  4. if an INSTEAD OF trigger is defined, it is run using OLD and NEW as available at this point
  5. if no INSTEAD OF trigger is defined, the database modifies the row according to its normal logic; for updateable view this may involve modifying one or more other tables to achieve the desired effect; if a view is not updatable, and no INSTEAD OF trigger is provided, an error is raised
  6. each row-level AFTER trigger fires, and is given NEW and OLD, but its changes to NEW are either disallowed or disregarded
  7. each statement-level AFTER trigger is fired
  8. implied triggers are fired, such as refrencial action in support of foreign key constraints: on-update or on-delete CASCADE, SET NULL, and SET DEFAULT rules
In ACID databases, an exception raised in a trigger will cause the entire stack of operations to be rolled back, including the original statement.

Sunday, January 17, 2010

How do manage / connect to SQL Server Express


Share/Save/Bookmark
Updated: 6/20/2008 12:25:00 AM
Requests: 150196
a.k.a. "Where is Enterprise Manager?"
a.k.a. "When will Express Manager be released?"
Microsoft has released a trmmed-down version of Management Studio, called Management Studio Express. You can download it from Microsoft Downloads. If you're brave, feel free to download the recent CTP of the tool here, I just can't really tell you yet whether anything worthwhile has been added or, more importantly, if anything useful has become broken.
If you are affected by the limitations of this free tool, you can manage SQL Server Express with a host of other tools:
  • OSQL 
  • SQLCMD 
  • any Express product 
  • Yohz Software's 
  • Lloyd Sheen's 
  • Simego's
Allegedly, you can also manage Express Edition with web data Administrator, but only if you enable mixed authentication (I haven't tried this, and note also that it is not officially supported).
There is no longer any such thing as Enterprise Manager or Query Analyzer, so stop looking for them, and don't try to use existing installations to connect to SQL Server 2005 instances—it simply will not work, even if it seems to at first glance.
As for connecting to Express from application code, this should not be any different from connecting to a named instance of SQL Server 2000. Your connection string should look like this, assuming local machine and an instance name of SQLEXPRESS (you might need a different instance name, and you may have to use a machine name, rather than "." (which means local)).
ConnectionString = "Provider = SQLNCLI;" & _
    "Data Source = .\SQLEXPRESS;" & _
    "Initial Catalog = ;" & _
    "User ID = ;" & _
    "Password = ;"

However, you might come across various errors, depending on your configuration and the tool you are using:
Sqlcmd: Error : Microsoft OLE DB Provider for SQL Server :
Client unable to establish connection.
 
Shared Memory Provider: The specified module could not be found.
 
Shared Memory Provider: The parameter is incorrect.
(Microsoft SQL Server, Error: 87)
 
Named pipes provider: The system cannot find the file specified
 
[DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied.
 
Shared Memory Provider: The system cannot find the file specified.
So in addition to the connection string above, some other steps you might have to perform:
  • Make sure that SQL Server Express is functioning properly:
     
    • Start / Run... / type "CMD" without the quotes and hit OK
    • Type "SQLCMD -S.\SQLEXPRESS" without the quotes and hit Enter
    • Verify that you<

    from : http://www.aspfaq.com/

Share/Save/Bookmark
How to use SQL Server Express (where's the UI?) - level 200
If you are used to working with SQL Server 2000, you may expect to find a tool similar to Enterprise Manager and Query Analyzer.  SQL Express is a free product, and it shows, but you get an awful lot for free. . . but you don't get it all.  I think that's perfectly fine.  I'd rather have something for free than nothing.
Here's a few tips to get you started:
  • SQL Express installs as a local instance named "SQLEXPRESS", so your connection string needs to include the instance name:  ".\SQLEXPRESS" or "localhost\SQLEXPRESS".
  • SQL Server Configuration Manager isn't the UI you want to add databases, tables, etc.
  • Use any of the Visual Studio Express products as your database UI.  They all have the database manager built in.
    • Use the Server Explorer window to add your database instance.  Then you can use it to add a new database and add tables to that database. 
    • If you have database create scripts, you can run them inside Visual Studio Express.  If you are used to hitting F5 in Query Analyzer, then you'll want to map a shortcut key to the "Run Selection" command: Right click -> Run Selection.
    • You can create all your database objects here.
    • You can run and step through stored procedures for debugging.

  • You can also use osql.exe to manager your database.  This is useful when you want to automate database scripts using NAnt.
  • You have the option of how you want to connect to a SQL Express database:
    • Through the SqlClient provider: Data Source=localhost\sqlexpress;Initial Catalog=MyNewTestDatabase;Integrated Security=True;Pooling=False
    • Through a file reference: Data Source=.\SQLEXPRESS;AttachDbFilename=C:\opensvn\development\ezweb\trunk\src\website\App_Data\ASPNETDB.MDF;Integrated Security=True;User Instance=True
    • If using ASP.NET, you already have a connection string you can use: LocalSqlServer:  Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|ASPNETDB.MDF;Integrated Security=True;User Instance=True 


    from : http://codebetter.com

Thursday, January 14, 2010


Share/Save/Bookmark
MYSQL
MySQL is a (RDBMS) that has more than 11 million installations. MySQL is named after Monty Widenius's daughter My. The program runs as a server providing multi-user access to a number of databases. MySQL is officially pronounced  (My S-Q-L), but often pronounced  (My SeQueL)
The project has made its source code available under the terms of the GNU General Public License, as well as under a variety of propietary agreements. MySQL is owned and sponsored by a single for profit firm, the Swedish company MySQL AB, now a subsidiary of sun microsystem] As of 2009 Oracle Corpoation began the process of acquiring Sun Microsystems.
In response to the Oracle acquisition, members of the MySQL community have created several forks such as Drizzle and Maria DB in fear that Oracle would hurt the development of MySQL because it is a competitor to the company's own database products.
MySQL is often used in free software projects that require a full-featured database management system, including projects such as WordPress, phpBB and other software built on the LAMP software stack. It is also used in many high-profile, large-scale www products

from http://en.wikipedia.org/wiki/MySQL