Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
13 views57 pages

8 Database Development-Final

The document provides an overview of Microsoft Access, a relational database management system designed for small businesses and home use, detailing its features such as tables, queries, forms, reports, macros, and modules. It also discusses data types, field properties, advantages, and disadvantages of using MS Access, along with data validation rules and input masks for data entry control. Overall, it highlights how MS Access can be customized for various database tasks while noting its limitations for larger organizations.

Uploaded by

sidraawan306
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views57 pages

8 Database Development-Final

The document provides an overview of Microsoft Access, a relational database management system designed for small businesses and home use, detailing its features such as tables, queries, forms, reports, macros, and modules. It also discusses data types, field properties, advantages, and disadvantages of using MS Access, along with data validation rules and input masks for data entry control. Overall, it highlights how MS Access can be customized for various database tasks while noting its limitations for larger organizations.

Uploaded by

sidraawan306
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Database Development

using MS-Access
By
Irfan Abdullah
Introduction
• Microsoft Access is a Relational Database Management System (RDBMS),
designed primarily for home or small business use.
• Access has traditionally been known as a desktop database system because its
functions are intended to be run from a single computer (as opposed to a
client/server system where the database application is installed on a server, then
accessed from multiple client machines) across a network.
• However, Access also includes a web solution (for building "custom web apps")
that is integrated with SQL Server — a more powerful database product, also from
Microsoft) — for a more robust solution.
• Microsoft Access stores various types of data in a way that is easy to retrieve. It
includes various features in order to achieve this.
• Microsoft Access allows you to restrict the data that users enter into each field. It
also allows you to link related data across multiple tables. And it also provides
other useful features such as forms, reports, query builder, and more.
MS Access - Objects
• MS Access uses “objects" to help the user list and organize information, as
well as prepare specially designed reports. When you create a database,
Access offers you Tables, Queries, Forms, Reports, Macros, and Modules.
Databases in Access are composed of many objects but the following are
the major objects:
• Tables
• Queries
• Forms
• Reports
• Beside these there are other objects also which are:
• Macro
• Module
• Together, these objects allow you to enter, store, analyze, and compile your
data.
Table
Table is an object that is used to define and store data. When you
create a new table, Access asks you to define fields which is also known
as column headings.
• Each field must have a unique name, and data type.
• Tables contain fields or columns that store different kinds of data,
such as a name or an address, and records or rows that collect all the
information about a particular instance of the subject, such as all the
information about a customer or employee etc.
• You can define a primary key, one or more fields that have a unique
value for each record, and one or more indexes on each table to help
retrieve your data more quickly.
Query
An object that provides a custom view of data from one or more tables.
Queries are a way of searching for and compiling data from one or
more tables.
• Running a query is like asking a detailed question of your database.
• When you build a query in Access, you are defining specific search
conditions to find exactly the data you want.
• In Access, you can use the graphical query by example facility or you
can write Structured Query Language (SQL) statements to create
your queries.
• You can define queries to Select, Update, Insert, or Delete data.
• You can also define queries that create new tables from data in one or
more existing tables.
Form
Form is an object in a desktop database designed primarily for
data input or display or for control of application execution. You
use forms to customize the presentation of data that your
application extracts from queries or tables.
• Forms are used for entering, modifying, and viewing records.
• The reason forms are used so often is that they are an easy way
to guide people toward entering data correctly.
• When you enter information into a form in Access, the data goes
exactly where the database designer wants it to go in one or
more related tables.
Report
Report is an object in desktop databases designed for formatting,
calculating, printing, and summarizing selected data.
• You can view a report on your screen before you print it.
• If forms are for input purposes, then reports are for output.
• Anything you plan to print deserves a report, whether it is a list of names
and addresses, a financial summary for a period, or a set of mailing labels.
• Reports are useful because they allow you to present components of your
database in an easy-to-read format.
• You can even customize a report's appearance to make it visually
appealing.
• Access offers you the ability to create a report from any table or query.
Macro
This object is a structured definition of one or more actions that you want
Access to perform in response to a defined event. An Access Macro is a script
for doing some job. For example, to create a button which opens a report,
you could use a macro which will fire OpenReport action.
• You can include simple conditions in macros to specify when one or more
actions in the macro should be performed or skipped.
• You can use macros to open and execute queries, to open tables, or to print
or view reports.
• You can also run other macros or Visual Basic procedures from within a
macro.
• Data macros can be attached directly to table events such as inserting new
records, editing existing records, or deleting records.
• Data macros in web apps can also be stand-alone objects that can be called
from other data macros or macro objects.
Module
Module is an object in desktop databases containing custom
procedures that you code using Visual Basic. Modules provide a more
discrete flow of actions and allow you to trap errors.
• Everything that can be done in a macro can also be done in a module,
but you don't get the macro interface that prompts you what is
needed for each action.
• Modules are far more powerful, and are essential if you plan to write
code for a multi-user environment, because macros cannot include
error handling.
• Modules can be standalone objects containing functions that can be
called from anywhere in your application, or they can be directly
associated with a form or a report to respond to events on the
associated form or report.
Microsoft Access Data Types
Type of Data Description Size
Text, including numbers which does not need calculation. (e.g.,
Short Text Up to 255 characters.
Mobile numbers).
Long Text This data type is used for lengthy text or alphanumeric data. Maximum 63, 999 characters.

Number Numeric data type used for storing mathematical calculations. 1, 2, 4, 8, and 16 bytes.

Date/Time Store Date/time for the years 100 through 9999. 8 bytes.
It allows you to store currency values and numeric data with
Currency 8 bytes.
one to four decimal places.
Assign a unique number or assigned by Microsoft Access when Four bytes (16 bytes if it is set as a
Auto Number
any new record is created. Usually used as the primary key Replication ID).
Yes/No It only stores logical values Yes and No. 1 bit
It stores files, such as digital photos. Multiple files can be
Attachment Up to 2 GB Data can be stored.
attached per record.
OLE objects can store audio, video, other Binary Large
OLE objects Up to 2 GB data can be stored.
Objects.
Text or combinations of text and numbers stored. That text is Each part of a Hyperlink data type allows
Hyperlink
used as hyperlink address. you to store a maximum 2048 characters.
Helps you to create an expression that uses data from one or You can create an expression which uses
Calculated
more fields. data from one or more fields.
Supported Field Properties
Property Use

Format Determines the way that the field appears when it is displayed or printed in datasheets or in forms or
reports that are bound to the field. You can use any valid number format. In most cases, you should set
the Format value to Currency.
Decimal Places Specifies the number of decimal places to use when displaying numbers.

Input Mask Displays editing characters to guide data entry. For example, an input mask might display a dollar sign
($) at the beginning of the field.
Caption The label text that is displayed for this field by default in forms, reports, and queries. If this property is
empty, the name of the field is used. Any text string is allowed.
An effective caption is usually brief.
Default Value Automatically assigns the specified value to this field when a new record is added.

Validation Rule Supplies an expression that must be true whenever you add or change the value in this field. Use in
conjunction with the Validation Text property.
Validation Text Enter a message to display when a value that is entered violates the expression in the Validation Rule
property.
Supported Field Properties
Property Use

Required Requires that data be entered in the field.

Indexed Specifies whether the field has an index. There are three available values:
• Yes (No duplicates) Creates a unique index on the field.
• Yes (Duplicates OK) Creates a non-unique index on the field.
• No Removes any index on the field.
Note: Do not change this property for a field that is used in a primary key.
Although you can create an index on a single field by setting the Indexed field property, some kinds of
indexes cannot be created in this manner. For example, you cannot create a multi-field index by setting
this property.
Text Align Specifies the default alignment of text within a control.
Advantages of MS Access
• Access offers a fully functional, relational database management system in minutes.
• Easy to import data from multiple sources into Access
• You can easily customize Access according to personal and company needs
• Microsoft Access online works well with many of the development languages that work on
Windows OS
• It is robust and flexible, and it can perform any challenging office or industrial database
tasks.
• MS-Access allows you to link to data in its existing location and use it for viewing,
updating, querying, and reporting.
• Allows you to create tables, queries, forms, and reports, and connect with the help of
Macros.
• Macros in Access is a simple programming construct with which you can use to add
functionality to your database.
• Microsoft Access online can perform heterogeneous joins between various data sets stored
across different platforms
Disadvantages of MS Access
• Microsoft Access database is useful for small-to-medium
business sectors. However, it is not useful for large-sized
organizations
• Lacks robustness compared to dbms systems like MS SQL
Server or Oracle
• All the information from your database is saved into one file.
This can slow down reports, queries, and forms
• Technical limit is 255 concurrent users. However, the real-world
limit is only 10 to 80 (depending on the type of application
which you are using)
Working with Tables
Control Data Entry Formats with Input Masks
Character Explanation
0 User must enter a digit (0 to 9).
9 User can enter a digit (0 to 9).
# User can enter a digit, space, plus or minus sign. If skipped, Access enters a blank space.
L User must enter a letter.
? User can enter a letter.
A User must enter a letter or a digit.
a User can enter a letter or a digit.
& User must enter either a character or a space.
C User can enter characters or spaces.
.,:;-/ Decimal and thousands placeholders, date and time separators. The character you select depends on
your Microsoft Windows regional settings.
> Coverts all characters that follow to uppercase.
< Converts all characters that follow to lowercase.
! Causes the input mask to fill from left to right instead of from right to left.
\ Characters immediately following will be displayed literally.
"" Characters enclosed in double quotation marks will be displayed literally.
Input Mask Examples
This input mask Provides this type of value Notes
(000) 000-0000 (206) 555-0199 In this case, you must enter an area code because that
section of the mask (000, enclosed in parentheses) uses
the 0 placeholder.
(999) 000-0000! (206) 555-0199 In this case, the area code section uses the 9
( ) 555-0199 placeholder, so area codes are optional. Also, the
exclamation point (!) causes the mask to fill in from left
to right.
(000) AAA-AAAA (206) 555-TELE Allows you to substitute the last four digits of a U.S.
style phone number with letters. Note the use of the 0
placeholder in the area code section, which makes the
area code mandatory.
#999 -20 Any positive or negative number, no more than four
2000 characters, and with no thousands separator or decimal
places.
Input Mask Examples
This input mask Provides this type of value Notes
>L????L?000L0 GREENGR339M3 A combination of mandatory (L) and optional (?) letters
MAY R 452B7 and mandatory numbers (0). The greater-than sign
forces users to enter all letters in uppercase. To use an
input mask of this type, you must set the data type for
the table field to Text or Memo.
00000-9999 98115- A mandatory postal code and an optional plus-four
98115-3007 section.
>L<?????????????? Maria A first or last name with the first letter automatically
Pierre capitalized.
ISBN 0- ISBN 1-55615-507-7 A book number with the literal text, mandatory first and
&&&&&&&&&-0 last digits, and any combination of letters and
characters between those digits.
Data Validation Rule
• Microsoft Access lets its user validate data entry by using its powerful feature ‘validation
rule’ for preventing data entry error message. Besides that, it also facilities users to
display error messages in case of invalid data entry.

• By writing simple and easy expressions in Access validation fields user can organize data
entries from various fields & apply validation rules on it.

• MS Access validation rule is one of the best options to prevent data-entry errors. Access
data validation rule actually checks the inserting data by applying a specified set of rules.
If your entered data doesn’t match the criteria applied for that field then it will show an
error message and rejects your data.

• Data validation rule works great for number, time/date fields, and currency. But you can
make a validation rule for the text entries also. Performing such a task can be a complex
one mainly if you are willing to test for many text variables.
Data Validation Rule
• When you select a field in table design, you see its Validation
Rule property in the lower pane.
• This rule is applied when you enter data into the field. You
cannot tab to the next field until you enter something that
satisfies the rule, or undo your entry.
• There is one trap to avoid. In some versions of Access, you will
not be able to leave the field blank once you add the validation
rule, i.e. you must enter something that satisfies the rule. If you
need to be able to leave the field blank, add OR Is Null to your
rule.
Validation Text
• Use in conjunction with the validation rule to create an error
message that appears when a user enters a prohibited value.
List Of Operators Used For Validation Rules
Operator Function

Not Tests for converse values. Use before any comparison operator except IS NOT
NULL.

In Value must be in the specified list.

Between Value must be in the range specified

Like Use wildcard character * to define the pattern of a valid string value

Is Not Null Value must be entered in the field. This is the same as setting the Required field
property to Yes. The benefit of using a validation rule here is that you can specify
validation text which is more user friendly than the default one for the required
field property.
List Of Operators Used For Validation Rules
Operator Function

And Specifies that all parts of the validation rule must be true.

Or Value can be any of the values specified

< Less than.

<= Less than or equal to.

> Greater than.

>= Greater than or equal to.

= Equal to.

<> Not equal to.


Validation Rule Examples
To do this ... Validation Rule for Fields Explanation
Any character outside the range A to Z is
Accept letters (a - z) only Is Null OR Not Like "*[!a-z]*"
rejected. (Case insensitive.)
Any character outside the range 0 to 9 is
Accept digits (0 - 9) only Is Null OR Not Like "*[!0-9]*" rejected. (Decimal point and negative sign
rejected.)
Is Null Or Not Like "*[!a-z OR ""
Letters and spaces only Punctuation and digits rejected.
""]*"
Is Null OR Not Like "*[!((a-z) or Accepts A to Z and 0 to 9, but no
Digits and letters only
(0-9))]*" punctuation or other characters.
The question mark stands for one
Exactly 8 characters Is Null OR Like "????????"
character.
Is Null OR Between 1000 And
For Number fields.
Exactly 4 digits 9999
Is Null OR Like "####" For Text fields.
Remove the "=" if zero is not allowed
Positive numbers only Is Null OR >= 0
either.
Validation Rule Examples
To do this ... Validation Rule for Fields Explanation
100% is 1. Use 0 instead of -1 if negative percentages
No more than 100% Is Null OR Between -1 And 1
are not allowed.
Not a future date Is Null OR <= Date()
Requires at least one character, @, at least one
Is Null OR ((Like "*?@?*.?*")
Email address character, dot, at least one character. Space, comma,
AND (Not Like "*[ ,;]*"))
and semicolon are not permitted.
Same as setting the field's Required property, but lets
You must fill in Field1 Not Null you create a custom message (in the Validation
Text property.)
It is better to use a lookup table for the list, but this
Limit to specific Is Null OR "M" Or "F"
may be useful for simple choices such as Male/Female.
choices
Is Null OR IN (1, 2, 4, 8) The IN operator may be simpler than several ORs.
The Yes/No field in Access does not support Null as
other databases do. To simulate a real Yes/No/Null
Yes/No/Null field Is Null OR 0 or -1
data type, use a Number field (size Integer) with this
rule. (Access uses 0 for False, and -1 for True.)
Validation Rules Alternatives
Use these alternatives instead of or in combination with validation rules:

• Required: Setting a field's Required property to Yes forces the user to enter something. (In
addition to the obvious cases, always consider setting this to Yes for your foreign key fields. See #3
in this article for details.)
• Allow Zero Length: Setting this property to No for text, memo, and hyperlink fields prevents a
zero-length string being entered. A ZLS is not the same as a Null, so if you permit this you have
confusing data for the user, more work checking for both as a developer, more chance of a mistake,
and slower executing queries. More information in Problem Properties.
• Indexed: To prevent duplicates in a field, set this property to Yes (No Duplicates). Using the
Indexes box in table design, you can create a multi-field unique index to the values are unique
across a combination of fields.
• Lookups: Rather than creating a validation rule consisting of a list of valid values, consider
creating a related table. This is much more flexible and easier to maintain.
• Input Mask: Of limited use. Users must enter the entire pattern (without them you can enter some
dates with just 3 keystrokes, e.g. 2/5), and they cannot easily insert a character if they missed one.
Working with Forms
Forms
Form is an object in a desktop database designed primarily for
data input or display or for control of application execution. You
use forms to customize the presentation of data that your
application extracts from queries or tables.
• Forms are used for entering, modifying, and viewing records.
• The reason forms are used so often is that they are an easy way
to guide people toward entering data correctly.
• When you enter information into a form in Access, the data goes
exactly where the database designer wants it to go in one or
more related tables.
Creating Form
• Access makes it easy to create a form from any table in your
database. Any form you create from a table will let you view the
data that's already in that table and add new data. Once you've
created a form, you can modify it by adding additional fields and
design controls like combo boxes.
Structure Query Language (SQL)
Introduction to SQL
• SQL is a standard language for accessing and manipulating
databases.
• SQL stands for Structured Query Language
• SQL lets you access and manipulate databases
• SQL became a standard of the American National Standards Institute
(ANSI) in 1986, and of the International Organization for
Standardization (ISO) in 1987.
• Although SQL is an ANSI/ISO standard, there are different versions
of the SQL language. However, to be compliant with the ANSI
standard, they all support at least the major commands (such as
SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar
manner.
What Can SQL do?
• SQL can execute queries against a database
• SQL can retrieve data from a database
• SQL can insert records in a database
• SQL can update records in a database
• SQL can delete records from a database
• SQL can create new databases
• SQL can create new tables in a database
• SQL can create stored procedures in a database
• SQL can create views in a database
• SQL can set permissions on tables, procedures, and views
The Most Important SQL Commands
• SELECT - extracts data from a database
• UPDATE - updates data in a database
• DELETE - deletes data from a database
• INSERT INTO - inserts new data into a database
• CREATE DATABASE - creates a new database
• ALTER DATABASE - modifies a database
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table
• CREATE INDEX - creates an index (search key)
• DROP INDEX - deletes an index
SQL (DML) Queries
SQL SELECT Statement
• The SELECT statement is used to select data from a database.
• The data returned is stored in a result table, called the result-set.
• SELECT Syntax :
SELECT column1, column2, ...
FROM table_name;
• If you want to select all the fields available in the table, use the
following syntax:
SELECT * FROM table_name;
• Example
SELECT CustomerName, City FROM Customers;
SQL WHERE Clause
• The WHERE clause is used to filter records.
• It is used to extract only those records that fulfill a specified
condition.
• WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
• Example
SELECT * FROM Customers
WHERE Country='Pakistan';

SELECT * FROM Customers


WHERE CustomerID=1;
Operators in The WHERE Clause
Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> Not equal. Note: In some versions of SQL this
operator may be written as !=
BETWEEN Between a certain range
LIKE Search for a pattern
IN To specify multiple possible values for a column
SQL ORDER BY Keyword
• The ORDER BY keyword is used to sort the result-set in ascending or
descending order.
• The ORDER BY keyword sorts the records in ascending order by default.
To sort the records in descending order, use the DESC keyword.
• ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
• Example
SELECT * FROM Customers
ORDER BY Country;

SELECT * FROM Customers


ORDER BY Country ASC, CustomerName DESC;
The SQL GROUP BY Statement
• The GROUP BY statement groups rows that have the same values into summary
rows, like "find the number of customers in each country".
• The GROUP BY statement is often used with aggregate functions (COUNT(),
MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.
• GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
• Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
SQL INNER JOIN Keyword
• The INNER JOIN keyword selects records that have matching values
in both tables.
• INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
• Example
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
The SQL INSERT INTO Statement
• The INSERT INTO statement is used to insert new records in a table.
• It is possible to write the INSERT INTO statement in two ways:

1. Specify both the column names and the values to be inserted.


2. If you are adding values for all the columns of the table, you do not need to
specify the column names in the SQL query. However, make sure the order of
the values is in the same order as the columns in the table.
• INSERT INTO syntax

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

INSERT INTO table_name


VALUES (value1, value2, value3, ...);
The SQL INSERT INTO Statement
• Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Ashmal', 'Ali', 'Gulshan-e-Iqbal', 'Karachi', '75400', 'Pakistan');

INSERT INTO Customers


VALUES ('Ashmal', 'Ali', 'Gulshan-e-Iqbal', 'Karachi', '75400', 'Pakistan');

INSERT INTO Customers (CustomerName, Address, City, Country)


VALUES ('Ashmal', 'Gulshan-e-Iqbal', 'Karachi', 'Pakistan');
The SQL DELETE Statement
• The DELETE statement is used to delete existing records in a
table.
• DELETE Syntax
DELETE FROM table_name WHERE condition;
• Example
DELETE FROM Customers WHERE CustomerName='Moiz Mansoor';
The SQL UPDATE Statement
• The UPDATE statement is used to modify the existing records in
a table.
• UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
• Example
UPDATE Customers
SET ContactName = ‘Sarah Amin', City= ‘Lahore'
WHERE CustomerID = 4;
SQL (DDL) Queries
The SQL CREATE TABLE Statement
• The CREATE TABLE statement is used to create a new table in a database.
• CREATE TABLE Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
....);
• Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
SQL Create Constraints
• Constraints can be specified when the table is created with the
CREATE TABLE statement, or after the table is created with the
ALTER TABLE statement.
• SQL Create Constraints Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
SQL Create Constraints
• SQL constraints are used to specify rules for the data in a table.
• Constraints are used to limit the type of data that can go into a table. This ensures
the accuracy and reliability of the data in the table. If there is any violation
between the constraint and the data action, the action is aborted.
• Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
• The following constraints are commonly used in SQL:
• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table
• FOREIGN KEY - Prevents actions that would destroy links between tables
• CHECK - Ensures that the values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column if no value is specified
• CREATE INDEX - Used to create and retrieve data from the database very quickly
SQL NOT NULL & UNIQUE KEY
Constraints
• By default, a column can hold NULL values.
• The NOT NULL constraint enforces a column to NOT accept NULL values.
• The UNIQUE constraint ensures that all values in a column are different.
• Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for
a column or set of columns.
• A PRIMARY KEY constraint automatically has a UNIQUE constraint. However, you can
have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per
table.
• SQL NOT NULL & UNIQUE KEY Contraint Example
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
SQL PRIMARY KEY Constraint
• The PRIMARY KEY constraint uniquely identifies each record in a table.
• Primary keys must contain UNIQUE values, and cannot contain NULL values.
• A table can have only ONE primary key; and in the table, this primary key can
consist of single or multiple columns (fields).
• SQL PRIMARY KEY Contraint Example (SQL Server / Oracle / MS Access)
CREATE TABLE Persons ( CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY, ID int NOT NULL,
LastName varchar(255) NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255), FirstName varchar(255),
Age int Age int,
); PRIMARY KEY (ID)
OR );
SQL PRIMARY KEY Constraint on Multiple Column

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
SQL FOREIGN KEY Constraint
• The FOREIGN KEY constraint is used to prevent actions that would
destroy links between tables.
• A FOREIGN KEY is a field (or collection of fields) in one table, that
refers to the PRIMARY KEY in another table.
• The table with the foreign key is called the child table, and the table
with the primary key is called the referenced or parent table.
• SQL FOREIGN KEY Contraint Example
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int CONSTRAINT FOREIGN KEY REFERENCES
Persons(PersonID)
);
SQL CHECK Constraint
• The CHECK constraint is used to limit the value range that can be
placed in a column.
• If you define a CHECK constraint on a column it will allow only
certain values for this column.
• If you define a CHECK constraint on a table it can limit the values in
certain columns based on values in other columns in the row.
• SQL CHECK Constraint Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);
SQL DEFAULT Constraint
• The DEFAULT constraint is used to set a default value for a column.
• The default value will be added to all new records, if no other value is
specified.
• SQL DEFAULT Constraint Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
SQL ALTER TABLE Statement
• The ALTER TABLE statement is used to add, delete, or modify
columns in an existing table.
• The ALTER TABLE statement is also used to add and drop
various constraints on an existing table.
• ALTER TABLE - ADD Column Syntax
ALTER TABLE table_name
ADD column_name datatype;
• Example
ALTER TABLE Customers
ADD Email varchar(255);
SQL ALTER TABLE Statement
• ALTER TABLE - DROP COLUMN Syntax
ALTER TABLE table_name
DROP COLUMN column_name;
• Example
ALTER TABLE Customers
DROP COLUMN Email;

• ALTER TABLE - ALTER/MODIFY COLUMN Syntax


• Use to change the data type of a column in a table

ALTER TABLE table_name


ALTER COLUMN column_name datatype;
• Example
ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;
The SQL DROP TABLE Statement
• The DROP TABLE statement is used to drop an existing table in
a database.
• DROP TABLE Syntax
DROP TABLE table_name;
• Example
DROP TABLE Shippers;

You might also like