You are on page 1of 11

Relational Database Concepts

Relational databases apply mathematical theories to efficiently organize and retrieve data
within a database. Database information is stored in tables, which are made up of rows
and columns. The following graphic shows several components of a database.

The following table describes common relational database components.


Component Description

Table

A table is a collection or set of related data within a database. A database can


contain one or more tables. Data within the table is organized as follows:
The table itself defines an object class. Data within the table is a
collection of discrete items that share common characteristics. In the
example above, the table contains data related to employees.
Rows identify specific instances of an object. In the above example,
each row identifies a distinct employee.
Columns identify attributes that describe, define, or are associated
with the object instances. In this example, each employee has
common attributes of EmployeeID, LastName, FirstName, and
Extension.

Primary
Key

Values for each row and column identify the exact characteristics of
each object instance. For example, the LastName of the second
employee in the table is King.

A primary key is a set of columns guaranteed to have unique values for each
row in a table. For example, in the table above, the EmployeeID column is
the primary key. Each column in any individual row identified by that
primary key will contain a unique ID number for each employee.

A foreign key defines the relationship and correspondence between columns


in one table and primary keys in another table. For example, another table
Foreign key
might use the Extension value as its primary key. In this situation, the
Extension value would be a foreign key for the table in the example.

In addition to the database itself, a relational database system includes a database


management system (DBMS). The role of the DBMS is to define the database structure,
maintain relationships within the database, control data access and modification, interact
with physical server resources, and define data recovery methods. The following table
describes several common features of a DBMS.
Feature

Queries

Description
To view or modify data, submit a query to the DBMS.
Queries are written in a structured language that is understood by
the DBMS. For example, SQL server uses Transact-SQL as the
query language.
Client applications submit queries to the DBMS. For example,
database management tools are client applications that connect to
and submit queries to the DBMS.
The DBMS executes the query and returns the result to the client.

Use queries to both view and modify data in the database.

Some queries submitted to the DBMS might request information stored in


Searching and multiple rows within a table or across tables or databases. The DBMS uses
Indexing
indexes to organize data for frequent searches to improve performance and
data access.

Locking

Most data management systems support multiple user access to a single


database. This means that at any time, the host system can have multiple
clients connected, all accessing different portions of the same database. To
coordinate changes to the database, the DBMS can use locking.
Locking prevents multiple users from changing the same piece of
data at the same time.
When a client needs to modify data, the table or row is locked,
allowing only that client to make the necessary changes. Other
clients will be unable to modify the data while it is locked,
although in many cases they will still be able to see it while it is
locked.

Transactions

After the changes are made, the lock is released, at which time
other clients can lock the data for modification.

A transaction is a group of actions that are treated as a single unit.


Transactions ensure data integrity. The success of the entire transaction
depends on the success of each of the actions that are part of a transaction.
None of the changes are made if errors are encountered in any part of the
transaction. When using transactions:
The application signals the start of the transaction.
The application submits the series of actions that are part of the
transaction. Each action is executed by the DBMS. All actions
performed by the application are considered part of the same

transaction.
The application signals the end of the transaction. If the end of the
transaction has been reached without error, the transaction is
committed and the changes become permanent.
If there is an error during the transaction, the DBMS rolls back the
changes, putting the database in its original (unchanged) state.

Transactions are particularly useful in processing changes that are made


across databases or across servers. For example, if you were transferring
money from one bank account to another account, the transaction might
involve servers at two different banks. The transaction would not be
completed unless the withdrawal from one account and the deposit into the
other account were both successful.

SQL Tool Facts


SQL Server 2000 allows you to access and administer your databases through either SQL
Server Enterprise Manager or SQL Query Analyzer, both of which are implemented as
clients. This means that you must use the tools to first establish a connection to the SQL
Server 2000 server, either locally or remotely, before performing your administrative
tasks. The table below describes the SQL Server 2000 tools, and how you can use them.
Tool

Description
Enterprise Manager runs as a snap-in for the MMC (Microsoft
Management Console). Through Enterprise Manager you can:

SQL Server
Enterprise
Manager

SQL Query
Analyzer

Connect to your databases


Administer your server configuration
Manage databases
Access the other SQL Server 2000 tools

Start, pause, and stop services

With Query Analyzer, you use Transaction-SQL statements to perform


tasks such as:

Perform administrative tasks


Create and run queries
Create database objects
Copy databases
Execute stored procedures
Troubleshoot query performance issues

You can access Query Analyzer from the Start menu, from Enterprise

Manager, or through the Run option using the Lsqlw command.


SQL Server
Use SQL Server Service Manager to manage the services associated
Service Manager with SQL server. You can access Service Manager through the Start
menu or through Enterprise Manager.
SQL Profiler gives you the ability to monitor SQL Server 2000 events.
By creating traces and filters in SQL Profiler, you can:

SQL Profiler

Monitor performance of a specific SQL Server instance


Debug TSQL statements and stored procedures
Identify queries that execute slowly
Capture events on a live system and replay them on a test system
for troubleshooting purposes
Perform security auditing tasks

Access SQL Profiler through the Start menu or Enterprise Manager.


Client Network
Utility

Server Network
Utility

Use the Client Network Utility to set the client Net-Libraries and to
define server aliases.
Use the Server Network Utility to set the server Net-Libraries.
Additionally, the Server Network Utility allows you to specify the
following parameters:
The network protocol stacks where SQL Server 2000 listens for
client requests
The order in which protocols are used for establishing
connections

The network addresses that SQL Server 2000 listens on

Osql

Osql is a command line utility used to run TSQL statements,


procedures, and scripts.

BCP

BCP is a command line utility that you can use to copy data from SQL
Server 2000 to a user-defined data file.

SQL Databases and Objects


As you study this section, answer the following questions:

Which database holds system-level data?


What is the purpose of the tempdb database?
How does a user database differ from a system database?
What is an object?
What is a stored procedure?

What is a trigger?
What does the data type identify?
How is the Money class represented?
How can dates be represented?

SQL Database and Object Facts


SQL Server 2000 has two types of databases:

System databases are used to store information about SQL Server 2000 and to
operate and manage the system. System databases should not be modified by
users or administrators.
User databases are the databases created by users for storing their unique data.

The following system databases are created by default when SQL Server 2000 is
installed.
Database
Database
Type

master

This database records all system-level information for the SQL


Server 2000 system, including the existence of all other
databases and the location of their files, login account
information, and system configuration settings. A backup of the
master database should always be available.

model

This database is used as the template for all new databases.

msdb

This database is used by SQL Server Agent for recording


operators and scheduling jobs and alerts.

tempdb

This database is a temporary database that is used as a holding


area for all temporary tables, stored procedures, and temporary
worktables used by the relational database engine. This database
is recreated each time SQL Server is startedno data is saved
from one session to another.

distribution
databases

This type of database stores history and transaction data used in


replication. A distribution database is not created on installation
instead, it is created when SQL Server is configured for
replication activities. In some instances, multiple distribution
databases may be used.

System

User

Description

Sample
Databases

Two sample user databases are provided during installation as


learning tools and models for creating user databases.
pubs contains sample data for a fictitious publishing
company.

Northwind contains sample sales data for a fictitious


import/export company. These databases and their tables

are frequently used as examples in SQL Server Books


Online.
The various components of a database are known as objects. The following table
describes the objects that comprise a SQL Server database.
Object

Description

Tables

Database tables typically consist of columns and rows of data. The rows
represent unique records in the database, while the columns represent fields
within the record.

Views

Views identify the specific data that is displayed at any given time. Views
can specify that only certain rows or columns are visible, can aggregate
(summarize) data, or can collect data from more than one table and present
it as though it were from a single table.

Indexes

A database index is a structured list of the values in the table or view, and
the location of the rows containing that value. Indexes can be clustered,
where the data is sorted and stored based on the index key, or nonclustered,
where the structure of the index is separate from the data rows, and row
locators in the index point to the location of the data in either a clustered
index key or in a heap. (A table that is created with no index is called a
heap, and the data rows are stored in no particular order.)

Keys

Keys are used to identify columns. A primary key is a set of columns


guaranteed to have unique values for each row in a table; a foreign key
defines the relationship and correspondence between columns in one table
and primary keys in another table.

Stored
procedures

A stored procedure is a group of Transact-SQL statements compiled into a


single execution plan. Stored procedures are typically used to achieve
consistent implementation, improved performance, and a single point of
control for commonly performed tasks.

Constraints

Constraints allow you to define the rules for the values allowed in columns.
While there are other methods of enforcing data integrity (i.e., triggers,
rules, and defaults), using constraints is the standard method for enforcing
data integrity.

Defaults

Defaults specify the values to be used in a column when no value is


specified when a row is inserted.

Triggers

Triggers are a special class of stored procedures defined to execute


automatically whenever an UPDATE, INSERT, or DELETE statement is
issued against a table or view. Tables can have multiple triggers. Triggers
can be used to enforce business rules and automate processing for a
company.

User-defined User-defined data types are based on pre-defined SQL Server 2000 data
data types
types. User-defined data types are typically used when columns holding

similar classes of data must have the same base data type, length, and
nullability. User-defined data types are not supported in table variables.
User-defined functions are uniquely-named subroutines made up of one or
User-defined
more Transact-SQL statements customized by the user for a specific
functions
purpose.

Datatype Facts
Each column, variable, expression, and parameter in SQL Server 2000 has a related data
type. The data type identifies:

The type of data the object can contain (such as text or numeric data)
Any constraints on the maximum size of the data
For numeric data, the number of digits the number can contain (precision
attribute)
For numeric data, and the number of digits that can be stored to the right of the
decimal point (scale attribute)

As you define tables and other database objects and as you construct TSQL statements,
the data type is identified by using a keyword. The following table lists many common
datatype keywords. Note: This list is not comprehensive.
Class

Integer

Bit, Decimal,
Numeric, and
Approximate
Numerics

Money

Keyword

Description

bigint

Integer (whole number) data from -263 (9,223,372,036,854,775,808) through 263-1


(9,223,372,036,854,775,807).

int

Integer (whole number) data from -231 (2,147,483,648) through 231-1 (2,147,483,647).

smallint

Integer data from -215 (-32,768) through 215-1 (32,767).

tinyint

Integer data from 0 through 255.

bit

Integer data with either a 1 or 0 value.

decimal

Fixed precision and scale numeric data from -1038+1


through 1038-1.

numeric

Functionally equivalent to decimal.

float

Floating precision number data with the following


valid values: -1.79E + 308 through -2.23E - 308, 0 and
2.23E + 308 through 1.79E + 308.

real

Floating precision number data with the following


valid values: -3.40E + 38 through -1.18E - 38, 0 and
1.18E - 38 through 3.40E + 38.

money

Monetary data values from -263 (-

922,337,203,685,477.5808) through 263-1


(+922,337,203,685,477.5807), with accuracy to a tenthousandth of a monetary unit.
smallmoney

Monetary data values from -214,748.3648 through


+214,748.3647, with accuracy to a ten-thousandth of a
monetary unit.

datetime

Date and time data from January 1, 1753, through


December 31, 9999, with an accuracy of threehundredths of a second, or 3.33 milliseconds.

smalldatetime

Date and time data from January 1, 1900, through June


6, 2079, with an accuracy of one minute.

char

Fixed-length non-Unicode character data with a


maximum length of 8,000 characters.

varchar

Variable-length non-Unicode data with a maximum of


8,000 characters.

text

Variable-length non-Unicode data with a maximum


length of 231-1 (2,147,483,647)

Date/Time

Character Strings nchar


and Characters

Binary Strings

Fixed-length Unicode data with a maximum length of


4,000 characters.

nvarchar

Variable-length Unicode data with a maximum length


of 4,000 characters. sysname is a system-supplied
user-defined data type that is functionally equivalent to
nvarchar(128) and is used to reference database object
names.

ntext

Variable-length Unicode data with a maximum length


of 230-1 (1,073,741,823) characters.

binary

Fixed-length binary data with a maximum length of


8,000 bytes.

varbinary

Variable-length binary data with a maximum length of


8,000 bytes.

image

Variable-length binary data with a maximum length of


231-1 (2,147,483,647) bytes.

Other Data Types cursor

A reference to a cursor.

sql_variant

A data type that stores values of various SQL Serversupported data types, except text, ntext, timestamp,
and sql_variant.

table

A special data type used to store a result set for later


processing.

timestamp

A database-wide unique number that gets updated


every time a row gets updated.

uniqueidentifier A globally unique identifier (GUID).


In addition to the system-supplied data types, user-defined data typesbased on system
data typescan be created for specific needs.
Building Queries
Use queries to interact with SQL server, view or modify data, or change the configuration
of the server. SQL server uses the Transact-SQL language for building and executing
queries. Even when you use a graphical administration tool or submit queries using
another supported language, the queries are translated into Transact-SQL statements and
then executed.
Queries are built using a series of statements, much like lines of programming code.
Queries can be simple or quite complex. The following example shows a simple query
statement that selects all columns from the Customers table for rows that match USA as
the country:
SELECT *
FROM Customers
WHERE Country = 'USA'

Note: The example shown above is a single query statement. Statements can be written
all on one line or broken into several lines as shown above. When SQL server parses the
query, it identifies all elements that are part of the statement and executes one statement
at a time.
Query statements can contain the following elements:
Component Description
Commands perform functions on the server or the database. Each statement
begins with a command. Four common commands are:
SELECT retrieves rows from a table
UPDATE changes data in a table
Commands
INSERT adds a row to a table or a view

Keywords

DELETE removes rows from a table

Keywords are words that SQL uses for its own functionality. Keywords
include commands as well as command parameters. In the example shown
above, the FROM and WHERE are keywords.
Note: Within documentation, keywords are written in all capital letters.
When you write Transact-SQL statements, case does not matter.

Identifiers

Identifiers are names of objects such as the server, a database, a table or an


index. In the example above, Customers is an identifier that identifies the

table used within the query.

Functions

Functions are collections of commands defined on the SQL server. When


functions are executed, they return a value. SQL comes with pre-defined
functions (called system functions), or you can define your own functions.
Examples of functions include:
DB_ID and DB_NAME return the database ID or name
OBJECT_ID and OBJECT_NAME return the object ID or name
COL_NAME returns the column name
COL_LENGTH returns the length of a column
INDEX_COL returns an index column name
When calling functions, follow the function name with parenthesis ( ). Inside
include any parameters that must be passed to the function. For example:
The SELECT SUSER_NAME() statement returns the currently
logged on user

The SELECT DB_ID('Northwind') statement returns the ID of the


Northwind database

An expression is a combination of identifiers, values, and operators that SQL


Expressions server can evaluate to get a result. In example above, both * and Country
= 'USA' are expressions.
Operators

Operators perform actions on data. For example, you can use arithmetic
operators to perform mathematical operations on the data.

Data types define the format of the data used by table columns or variables.
Each data type is identified by a keyword. When you are constructing
Data Types
statements, you might need to identify the data type of any variables used
within the statement.
Comments are nonexecuting remarks in a statement. Comments are indicated
in one of two ways:
Double hyphens ( -- ). Any text on a line following the double
hyphen will not be included as part of the statement. Text on a new
line that is not preceded by the double hyphens is not commented.
Forward slash-asterisk pairs ( /* ... */ ). Any text inside the
character pair will not be executed, even if it spans multiple lines.
Comments

For example, the following statement:


--get the list of names
SELECT Firstname /*, Lastname */
FROM Customers
WHERE Language = 'Spanish' --test for language

With the comments removed becomes:


SELECT Firstname
FROM Customers
WHERE Language = 'Spanish'

When you look up commands in the SQL documentations, you will see something like
the following:
SELECT select_list
[INTO new_table_name]
FROM table_list
[WHERE search_conditions]
[GROUP BY group_by_list]
[HAVING search_conditions]
[ORDER BY order_list [ASC | DESC] ]

Be aware of the following when working with commands and documentation:

Keywords are in all capital letters.


Italics indicate identifiers, expressions, or functions.
Items in brackets [ ] are optional. In this example, only the SELECT and FROM
components of the statement are required.

You might also like