0% found this document useful (0 votes)
255 views92 pages

Introduction To MS Access Without Answers

Microsoft Access is a database management system from Microsoft that combines the relational Microsoft Jet Database Engine with a graphical user interface and development tools. It allows users to create databases for storing data in tables and link related information. Within an Access database, the main objects are tables, queries, forms, reports, macros, and modules which allow users to define, enter, organize, and present data.

Uploaded by

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

Introduction To MS Access Without Answers

Microsoft Access is a database management system from Microsoft that combines the relational Microsoft Jet Database Engine with a graphical user interface and development tools. It allows users to create databases for storing data in tables and link related information. Within an Access database, the main objects are tables, queries, forms, reports, macros, and modules which allow users to define, enter, organize, and present data.

Uploaded by

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

Introduction to MS

Access
MS. LESLYN BONACHITA - REAZOL
MS Access
 Microsoft Access is a Database Management
System (DBMS) from Microsoft that
combines the relational Microsoft Jet
Database Engine with a graphical user
interface and software development tools.
It is a part of the Microsoft Office suite of
applications, included in the professional
and higher editions.
MS Access - Overview
 Microsoft Access is a Database Management System (DBMS) from Microsoft
that combines the relational Microsoft Jet Database Engine with a
graphical user interface and software development tools. It is a member of
the Microsoft Office suite of applications, included in the professional and
higher editions.
 Microsoft Access is just one part of Microsoft’s overall data management
product strategy.
 It stores data in its own format based on the Access Jet Database Engine.
 Like relational databases, Microsoft Access also allows you to link related
information easily. For example, customer and order data. However,
Access 2013 also complements other database products because it has
several powerful connectivity features.
 It can also import or link directly to data stored in other applications and
databases.
MS Access - Overview
 As its name implies, Access can work directly with data from other sources,
including many popular PC database programs, with many SQL (Structured
Query Language) databases on the desktop, on servers, on minicomputers,
or on mainframes, and with data stored on Internet or intranet web servers.
 Access can also understand and use a wide variety of other data formats,
including many other database file structures.
 You can export data to and import data from word processing files,
spreadsheets, or database files directly.
 Access can work with most popular databases that support the Open
Database Connectivity (ODBC) standard, including SQL Server, Oracle, and
DB2.
 Software developers can use Microsoft Access to develop application
software.
MS Access - Overview
 Microsoft Access stores information which is called a
database. To use MS Access, you will need to follow these
four steps −
 Database Creation − Create your Microsoft Access database and
specify what kind of data you will be storing.
 Data Input − After your database is created, the data of every
business day can be entered into the Access database.
 Query − This is a fancy term to basically describe the process of
retrieving information from the database.
 Report (optional) − Information from the database is organized in a
nice presentation that can be printed in an Access Report.
MS Access – Overview: ARCHITECTURE
 Access calls anything that can have a name an object.
Within an Access desktop database, the main objects are
tables, queries, forms, reports, macros, data macros,
and modules.
 If you have worked with other database systems on
desktop computers, you might have seen the term
database used to refer to only those files in which you
store data.
 But, in Access, a desktop database (.accdb) also includes
all the major objects related to the stored data,
including objects you define to automate the use of your
data.
MS Access - RDBMS
 Microsoft Access has the look and feel of other Microsoft
Office products as far as its layout and navigational aspects
are concerned, but MS Access is a database and, more
specifically, a relational database.
 Before MS Access 2007, the file extension was *.mdb, but in
MS Access 2007 the extension has been changed
to *.accdb extension.
 Early versions of Access cannot read accdb extensions but MS
Access 2007 and later versions can read and change earlier
versions of Access.
 An Access desktop database (.accdb or .mdb) is a fully
functional RDBMS.
MS Access - RDBMS
 It provides all the data definition, data manipulation,
and data control features that you need to manage
large volumes of data.
 You can use an Access desktop database (.accdb or
.mdb) either as a standalone RDBMS on a single
workstation or in a shared client/server mode across a
network.
 A desktop database can also act as the data source for
data displayed on webpages on your company intranet.
 When you build an application with an Access desktop
database, Access is the RDBMS.
Data Definition
Let us now understand what Data Definition is −
 In document or a spreadsheet, you generally have complete freedom to define the
contents of the document or each cell in the spreadsheet.
 In a document, you can include paragraphs of text, a table, a chart, or multiple
columns of data displayed with multiple fonts.
 In spreadsheet, you can have text data at the top to define a column header for
printing or display, and you might have various numeric formats within the same
column, depending on the function of the row.
 An RDBMS allows you to define the kind of data you have and how the data should
be stored.
 You can also usually define rules that the RDBMS can use to ensure the integrity of
your data.
 For example, a validation rule might ensure that the user can’t accidentally store
alphabetic characters in a field that should contain a number.
Data Manipulation
 Working with data in RDBMS is very different from working
with data in a word processing or spreadsheet program.
 Ina word processing document, you can include tabular data and
perform a limited set of functions on the data in the document.
 You can also search for text strings in the original document and,
with ActiveX controls, include tables, charts, or pictures from
other applications.
 Ina spreadsheet, some cells contain functions that determine the
result you want, and in other cells, you enter the data that
provides the source information for the functions.
Data Manipulation
An RDBMS provides you many ways to work with your data. For
example,
 You can search a single table for information or request a
complex search across several related tables.
 You can update a single field or many records with a single
command.
 You can write programs that use RDBMS commands to fetch data
that you want to display and allow the user to update the data.
Access uses the powerful SQL database language to process data in
your tables. Using SQL, you can define the set of information that
you need to solve a particular problem, including data from
perhaps many tables.
Data Control
 Spreadsheets and word processing documents are great for
solving single-user problems, but they are difficult to use when
more than one person needs to share the data.
 When you need to share your information with others, RDBMS gives you
the flexibility to allow multiple users to read or update your data.
 An RDBMS that is designed to allow data sharing also provides features to
ensure that no two people can change the same data at the same time.
 The best systems also allow you to group changes (which is also known as
transaction) so that either all the changes or none of the changes appear
in your data.
 You might also want to be sure that no one else can view any part of the
order until you have entered all of it.
 Because you can share your Access data with other users, you might need to set
some restrictions on what various users are allowed to see or update.
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

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.
Other MS Access Objects
 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.
Other MS Access 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.
MS Access - Create Database
2 WAYS OF CREATING
DATABASE:
 CREATING A DATABASE USING A
TEMPLATE
 CREATING A BLANK DATABASE

 CREATING A DATABASE USING A


TEMPLATE
To create a database from a template, we first need to
open MS Access and you will see the following screen in
which different Access database templates are
displayed.
Select Select the first template. You will see more information
related to this template.

CREATING A
DATABASE After selecting a template related to your

USING A Enter requirements, enter a name in the File name field and
you can also specify another location for your file if
you want.

TEMPLATE
Now, press the Create option. Access will download
Press that database template and open a new blank database
Create Blank Database
Sometimes database requirements can be so
specific that using and modifying the existing
templates requires more work than just
creating a database from scratch. In such case,
we make use of blank database.

Step 1 − Let us now


start by opening MS
Access.
Create Blank Database

Step 2 − Select
Blank desktop
database. Enter
the name and
click the Create
button.
Create Blank Database

Step 3 − Access
will create a new
blank database
and will open up
the table which is
also completely
blank.
MS Access - Data Types
Every field in a table has properties and these properties define
the field's characteristics and behavior. The most important
property for a field is its data type. A field's data type
determines what kind of data it can store. MS Access supports
different types of data, each with a specific purpose.

 The data type determines the kind of the values that users
can store in any given field.
 Each field can store data consisting of only a single data
type.
MS Access - Data Types
Type of Description Size
Data
Text or combinations of text and numbers, including numbers that do not Up to 255 characters.
Short Text
require calculating (e.g. phone numbers).
Lengthy text or combinations of text and numbers. Up to 63, 999
Long Text
characters.
Numeric data used in mathematical calculations. 1, 2, 4, or 8 bytes (16
Number bytes if set to Replication
ID).

Date/Time Date and time values for the years 100 through 9999. 8 bytes

Currency values and numeric data used in mathematical calculations 8 bytes


Currency
involving data with one to four decimal places.
A unique sequential (incremented by 1) number or random number 4 bytes (16 bytes if set
AutoNumber assigned by Microsoft Access whenever a new record is added to a table. to Replication ID).

Yes and No values and fields that contain only one of two values (Yes/No, 1 bit.
Yes/No True/False, or On/Off).
 In Access 2013, we now have two data types —
short text and long text. In previous versions
of Access these data types were called text
and memo.

 The text field is referred to as short text and


your memo field is now called long text.
MS Access - Data Types
Data Types Description Size
Files, such as digital photos. Multiple files can be attached per Up to about 2 GB.
Attachment record. This data type is not available in earlier versions of
Access.
OLE objects can store pictures, audio, video, or other BLOBs Up to about 2 GB.
OLE objects
(Binary Large Objects)
Text or combinations of text and numbers stored as text and used Up to 8,192 (each part of a Hyperlink
Hyperlink as a hyperlink address. data type can contain up to 2048
characters).
The Lookup Wizard entry in the Data Type column in the Design Dependent on the data type of the
view is not actually a data type. When you choose this entry, a lookup field.
wizard starts to help you define either a simple or complex lookup
field.
Lookup Wizard
A simple lookup field uses the contents of another table or a value
list to validate the contents of a single value per row. A complex
lookup field allows you to store multiple values of the same data
type in each row.
You can create an expression that uses
You can create an expression that uses data from one or more
data from one or more fields. You can
Calculated fields. You can designate different result data types from the
designate different result data types
expression.
from the expression.
MS Access - Create Tables
 When you create a database, you store your data in tables.
Because other database objects depend so heavily on tables,
you should always start your design of a database by creating
all of its tables and then creating any other object. Before you
create tables, carefully consider your requirements and
determine all the tables that you need.
 After creating the fields save the table.
 Enter the name of your table in the Table Name field. Here
the tbl prefix stands for table.
 When creating a field name, you must enter data type and
description
 Then choose a primary key that will uniquely identify a
record.
Customize the
Blank Table
STEP 1. Select a Data Type
for the New Field.
Right-click Click to Add.
This combo box lists the data
types you can assign to a field.
Access requires that each field
is assigned a data type.
In this case, we're telling Access
to only allow Short Text in this
field. If a user tries to enter a
different data type, they will
receive an error.
Customize the
Blank Table
STEP 2. Name the Field
Once you've selected a
data type, the field header
will be highlighted with the
text Field1 so that you can
provide a name for the
field.

E.g. ArtistName
Customize the
Blank Table
STEP 3. Rename the First
Field
The first field in our table
is currently called ID.

Right-click on the ID field


header, and select
Rename Field. The field
will be highlighted for you
to rename it.
Enter ArtistId.
Customize the
Blank Table
STEP 4. Save the Table
Right-click on Table1 to
save the table.
Screenshot of entering a
name at the prompt.
Enter Artists at the prompt.

DB Table have 2 fields


(ArtistId and ArtistName)
Create a New Table
 Create a new table. This
one will contain
information on the albums
that the artists release, so
we'll call it Albums.

 STEP1. Create a New Table


Ensuring the Create tab is
selected on the Ribbon, click
Table.
This will add a blank table
called Table1 to the
database.
Create a New Table
 STEP2. Set up the Fields
Now add 4 fields and rename
the first. Set them up as
follows:
Field Name Data Type

AlbumId (Leave it as is)

AlbumName Short Text

ReleaseDate Date & Time

ArtistId Number

GenreId Number
Create a Table in Design View
 STEP2. Set up the Fields
Now add 4 fields and rename
the first. Set them up as
follows:
Field Name Data Type

AlbumId (Leave it as is)

AlbumName Short Text

ReleaseDate Date & Time

ArtistId Number

GenreId Number
Create a Table in Design View

 Design View can make it easier to set up a table. It provides a


different view of the table to Datasheet View, and is typically used
to configure the table.

 You can use Design View to create a tables, set up data types for
each field, specify default values, specify how data should be
entered and displayed, and more.
 Generally speaking, most tasks can be achieved using either Design
View or Datasheet View, however there are some advanced
settings that can only be changed in Design View. Also, you might
find that you prefer to do certain tasks in Design View and other
tasks in Datasheet View.
Datasheet View vs Design View
Datasheet View
 Datasheet View is what we used when we created our table
previously.
 Datasheet View displays the table as a grid. The fields are displayed
as columns, and the records are displayed as rows. The field names
are listed as the column headers.
 Datasheet View displays the data. If this table had data, it would be
displayed in the cells.
 Each row represents a record. If the table had say, five records,
there would be five rows of data.
 In Datasheet View, if you want to find out a field's data type, you
need to select that field, then select the Fields tab on the Ribbon.
The field's data type and other properties will be listed on the right
side of the Ribbon.
Datasheet View vs Design View
Design View
 Design View doesn't display any data. Therefore, there's more
space available to display other settings.
 InDesign View, the fields are listed vertically. They are listed
above and below each other as opposed to side-by-side.
 In Design View, you can see the data type listed next to each
field.
 The way Design View works is, when you click on a field (in the
top frame), the bottom frame displays the properties for that
field. You can then change these properties as required.
Create an Input Mask
 An input mask is a set of simple rules that specifies the
format in which data can be entered into a field.
 For example, an input mask of (999) 000-0000 could be used
to determine how phone numbers are entered. In this
example, the area code is optional, but the rest of the
number is must be entered. This is because, with any input
mask, a 9 specifies an optional number, a 0 specifies a
mandatory number.

 InDESIGN VIEW, click a FIELD NAME and go to GENERAL TAB,


then click INPUT MASK.
Customize the Input Mask
 To change the INPUT MARK LIST, click EDIT LIST
 Sample: 99->L<LL-0000

This specifies how the date should be entered. Here's an break down of
each part:
 The 99 part defines two optional numbers (i.e. for the day). So the user
has a choice of entering that part of the date. But if they do, it must
be a number.
 The >L specifies that the user must enter an uppercase letter for that
part of the date.
 The <LL specifies two lowercase letters for that part of the date.
 The 0000 specifies four numbers for that part of the date.
Add Data to a Table: DATASHEET, FORM, SQL
 Open Datasheet View and enter the Add Data using a Form
following data:
n many cases, you will want to create a
GenreId* Genre form for users to enter data. This will
allow them to enter data without needing
(Autonumber) Rock any technical knowledge about Microsoft
Access.
(Autonumber) Pop
Forms can also improve usability and
(Autonumber) Jazz
increase productivity. They can be used to
update data across multiple tables, saving
(Autonumber) Blues
the user from having to open multiple
(Autonumber) Hip Hop tables and enter data into each one. They
can also be use to provide extra data
validation.
Add Data to a Table: DATASHEET, FORM, SQL
 Add Data using SQL

 SQL(Structured Query
Language) is a query
language designed
specifically for relational
databases. Most relational
database management
systems use SQL.
Create a Relationship
 Access allows you to create relationships between tables so that you can
query related data from multiple tables.
 In relational database terms, a relationship is a situation where multiple
tables can contain related data that is linked by a common field.
 A relationship consists of a parent table and a child table. The child table
references the parent table by having a field that matches a field in the
parent table. The child's field is referred to as a foreign key. The parent's
field is the primary key.
 In a relationship, any data entered into the child's foreign key field must
match a value from the parent's primary key field.
 By ensuring that the foreign key's data matches data in the primary key,
we know that all records in the child table will have an associated record
in the parent table.
Create a Relationship
 Sample, ALBUMS and ARTISTS : STEP1: Open the Relationship Dialog
 Will have a one-to-many
relationship between the Click Relationships from the
Albums and Artists table. Our Database Tools tab on the Ribbon.
relationship will determine
that an artist can have many The Show Tables dialog box should
albums, but an album can only appear. If it doesn't appear, click
belong to one artist. Show Tables.
Create a Relationship

STEP 2. Select the Tables


 Select both the Artists
and Albums tables from
the list and click Add.
 ClickClose to close the
dialog box.
Create a Relationship
STEP 3 Create the Relationship

 Clickand drag the


Albums.ArtistId field over
the Artists.ArtistId field and
release.

 The Edit Relationships dialog


box appears.
Create a Relationship
STEP 4 Edit the Relationship
 Check Enforce Referential
Integrity and click Create.
 The Enforce Referential Integrity
option will ensure that child
records cannot reference a non-
existent parent.
 So if a user tries to enter an album
with an ArtistId that isn't in the
Artists table, Access will prevent
them from doing so.
 Access will also prevent the user
from deleting an artist that has
albums attached. Then SAVE.
Types of Relationships
 There are three types of relationships:

 One-to-One
A row in table A can have only one matching row in table B, and vice versa.
 One-to-Many (or Many-to-One)
A row in table A can have many matching rows in table B, but a row in table
B can have only one matching row in table A.
 Many-to-Many
A row in table A can have many matching rows in table B, and vice versa.
This is achieved through the use of a third table (commonly called a
junction table) that contains lookup data for both tables.
One-to-One
 A row in table A can have only one matching row in table B,
and vice versa.
 This is not a common relationship type, as the data stored in
table B could just have easily been stored in table A.
However, there are some valid reasons for using this
relationship type. A one-to-one relationship can be used for
security purposes, to divide a large table, and various other
specific purposes.
 In the above example, we could just as easily have put an
HourlyRate field straight into the Employee table and not
bothered with the Pay table. However, hourly rate could be
sensitive data that only certain database users should see. So,
by putting the hourly rate into a separate table, we can
provide extra security around the Pay table so that only
certain users can access the data in that table.
MS Access - Query Data
A query is a request for data results, and for action on data. You can use a query to
answer a simple question, to perform calculations, to combine data from different
tables, or even to add, change, or delete table data.
 As tables grow in size they can have hundreds of thousands of records, which
makes it impossible for the user to pick out specific records from that table.
 With a query you can apply a filter to the table's data, so that you only get the
information that you want.
 Queries that you use to retrieve data from a table or to make calculations are
called select queries.
 Queries that add, change, or delete data are called action queries.
 You can also use a query to supply data for a form or report.
 In a well-designed database, the data that you want to present by using a form
or report is often located in several different tables.
 The tricky part of queries is that you must understand how to construct one
before you can actually use them.
SQL
 SQL is a standard language for storing, manipulating and
retrieving data in databases.
What is SQL?
- 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
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
SQL CREATE DATABASE Statement
The CREATE DATABASE statement is used to create a new SQL
database.
Syntax
 CREATE DATABASE databasename;

 The following SQL statement creates a database called


"testDB":
Example
CREATE DATABASE testDB;
SQL DROP DATABASE Statement
The DROP DATABASE statement is used to drop an
existing SQL database.
Syntax
 DROP DATABASE databasename;
The following SQL statement drops the existing
database "testDB":
Example
 DROP DATABASE testDB;
SQL CREATE TABLE Statement
The CREATE TABLE  The following example
statement is used to create creates a table called
a new table in a database. "Persons" that contains five
columns: PersonID, LastName,
FirstName, Address, and City:
 Syntax  Example
CREATE TABLE table_name ( CREATE TABLE Persons (
column1 datatype, PersonID int,
column2 datatype, LastName varchar(255),
column3 datatype, FirstName varchar(255),
Address varchar(255),
....
City varchar(255)
); );
The SQL DROP TABLE Statement
The DROP TABLE statement is used to drop an existing table
in a database.
 Syntax
DROP TABLE table_name;

The following SQL statement drops the existing table


"Shippers":
 Example
DROP TABLE Shippers;
SQL TRUNCATE TABLE
The TRUNCATE TABLE statement is used to delete the data
inside a table, but not the table itself.
 Syntax
TRUNCATE TABLE table_name;
ACTIVITY 1

Create a TABLE
tblCustomer (with the following fields:
CustomerID, CustomerName, ContactName,
Address, City, PostalCode, and Country)
Database Tables
Create a Customer Table

CustomerID CustomerName ContactName Address City PostalCode Country


1 Jaylhin Kaye Reazol Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Jaylhin Noelle Ana Tranillo Avda. de la México 05021 Mexico
Bonachita Constitución 2222 D.F.
3 Jayzee Noel van Antonio Mataderos 2312 México 05023 Mexico
Huezin Moreno D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund

The table above contains five records (one for each customer) and seven columns
(CustomerID, CustomerName, ContactName, Address, City, PostalCode, and Country).
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.
 The following SQL statement selects all the records in the "Customers" table:
Example
 SELECT * FROM tblCustomer;
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;
Eg SELECT CustomerName FROM tblCustomer;

SELECT * FROM table_name;


Eg SELECT * FROM tblCustomer;
ACTIVITY 2

Select the "CustomerName"


and "City" columns from the
"Customers" table

ANSWER
SQL SELECT DISTINCT Statement

The SELECT DISTINCT statement is used to return only distinct (different)


values.
 Inside a table, a column often contains many duplicate values; and
sometimes you only want to list the different (distinct) values.
 SELECT DISTINCT Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name;
Eg SELECT DISTINCT City
FROM tblCustomer;
ACTIVITY 3

Select only the DISTINCT


values from the "Country"
column in the "Customers"
table
ANSWER
SQL WHERE Clause
The WHERE clause is used to filter records.
 The WHERE clause is used to extract only those records that fulfill a
specified condition.
 WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: The WHERE clause is not only used in SELECT statement, it is also
used in UPDATE, DELETE statement, etc.!
The following SQL statement selects all the customers from the country
"Mexico", In the "Customers" table:
SELECT * FROM Customers
WHERE Country='Mexico';
ACTIVITY 4

Select all the customers


from the city "Mexico D.F",
in the "Customer" table
ANSWER
Text Fields vs. Numeric Fields
 SQL requires single quotes around text values (most database systems will also allow double quotes).
However, numeric fields should not be enclosed in quotes:
Example
SELECT * FROM tblCustomer
WHERE CustomerID=1;
 Operators in The WHERE Clause

Operator Description Operator Description


= Equal <> Not equal. Note: In some versions of SQL this
operator may be written as !=
> Greater than
BETWEEN Between a certain range
< Less than
LIKE Search for a pattern
>= Greater than or equal
IN To specify multiple possible values for a
<= Less than or equal
column
<> Not equal. Note: In some versions of SQL this
operator may be written as !=
SAMPLES
 SELECT * FROM Products
WHERE Price = 18;

SELECT * FROM Products


WHERE Price > 30;

SELECT * FROM Products


WHERE Price BETWEEN 50 AND 60;

SELECT * FROM Customers


WHERE City LIKE ‘s*’;

SELECT * FROM Customers


WHERE City IN ('Paris','London');
ACTIVITY 5
Create a TABLE PRODUCT
FIELD NAME DATA TYPE DESCRIPTION

ProdNum Text Product control


number; PRIMARY KEY
ProdDes Text Description of the
product
StockonHand Number Quantity of Products on
Hand
SupplierCode Text Supplier of the Product

Price Currency Price of the product


TABLE PRODUCT
ProdNum ProdDes StockonHand SupplierCode Price
Printer01 Epson Printer 20 GInter01 4,500.00

Printer02 Acer Printer 10 GInter01 5,500.00


Computer01 Acer Desktop 10 Octagon01 32,000.00

Computer02 Acer Laptop 25 Octagon01 18,000.00

Computer03 Acer Notebook 20 Octagon01 15,000.00


Computer04 Lenovo Laptop 5 Emcor01 17,000.00

Tablet01 Acer Tablet 8 Emcor01 13,000.00


Tablet02 iPAD 5 Emcor01 25,000.00
Tablet03 Samsung Tablet 13 Octagon01 12,500.00
ACTIVITY 6
a. SELECT ALL PRODUCTS WHERE PRICE IS
GREATER THAN 15,000.00
b.SELECT ALL PRODUCTS WHERE PRICE IS
LESS THAN OR EQUAL TO 15,000.00
c. SELECT ALL PRODUCTS WHERE PRODUCT
DESCRIPTION STARTS WITH A

ANSWER
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


To add a column in a table, use the ff syntax:
 ALTER TABLE table_name
ADD column_name datatype;
The following SQL adds an "Email" column to the "Customers" table:

ALTER TABLE tblCustomer


ADD Email varchar(255);
ALTER TABLE - DROP COLUMN

To delete a column in a table, use the following syntax (notice


that some database systems don't allow deleting a column):
 ALTER TABLE table_name
DROP COLUMN column_name;
The following SQL deletes the "Email" column from the
"Customers" table:
ALTER TABLE tblCustomer
DROP COLUMN Email;
ALTER TABLE - ALTER/MODIFY COLUMN

To change the data type of a column in a table, use the


following syntax:
 SQL Server / MS Access:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
Now we want to change the data type of the column
named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
 ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;
SQL AND, OR and NOT Operators
 The WHERE clause can be combined with AND, OR, and NOT
operators.
 The AND and OR operators are used to filter records based
on more than one condition:
 The AND operator displays a record if all the conditions
separated by AND are TRUE.
 The OR operator displays a record if any of the conditions
separated by OR is TRUE.
 The NOT operator displays a record if the condition(s) is
NOT TRUE.
AND OR and NOT Syntax
 SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
 SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
 SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
ACTIVITY 7
A. Select
all fields from "Customers" where country is
"Germany" AND city is "Berlin“
B. Selectall fields from "Customers" where city is
"Berlin" OR "München“
C. Select
all fields from "Customers" where country is
"Germany" OR "Spain“
D. Select
all fields from "Customers" where country is
NOT "Germany"
ANSWER
Combining AND, OR and NOT
You can also combine the AND, OR and NOT operators.
The following SQL statement selects all fields from "Customers" where
country is "Germany" AND city must be "Berlin" OR "München" (use
parenthesis to form complex expressions):
 SELECT * FROM tblCustomer
WHERE Country='Germany' AND (City='Berlin' OR City='München’);
Select all fields from "Customers" where country is NOT "Germany" and
NOT "USA":
SELECT * FROM tblCustomer
WHERE NOT Country='Germany' AND NOT Country='USA';
ACTIVITY 8

Select all records where the


City column has the value
'Berlin' and the PostalCode
column has the value 12209.
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;
The following SQL statement selects all customers from the "Customers"
table, sorted by the "Country" column:
SELECT * FROM tblCustomer
ORDER BY Country;
ORDER BY DESC and ORDER BY Several Columns
 Select all customers from the "Customers" table, sorted DESCENDING by the
"Country" column
SELECT * FROM tblCustomer
ORDER BY Country DESC;
 Select all customers from the "Customers" table, sorted by the "Country" and
the "CustomerName" column. This means that it orders by Country, but if some
rows have the same Country, it orders them by CustomerName
SELECT * FROM tblCustomer
ORDER BY Country, CustomerName;
 Select all customers from the "Customers" table, sorted ascending by the
"Country" and descending by the "CustomerName"
SELECT * FROM tblCustomer
ORDER BY Country ASC, CustomerName DESC;
ACTIVITY 9

Select all records from the


Customers table, sort the
result alphabetically by the
column City
SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
 INSERT INTO Syntax:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
OR
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
SAMPLE: Insert 3 records in tblCustomer
INSERT INTO tblCustomer (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Nuelan Ian ','Mark Lovin','280 Street
Love','Helsinki','21240','Finland’);

INSERT INTO tblCustomer (CustomerName, ContactName, Address, City,


PostalCode, Country)
VALUES (‘Florence John’,‘Karl Matthew’,‘305 Suite B’,
‘Seattle’, ‘98128’, ‘USA’);

INSERT INTO tblCustomer (CustomerName, ContactName, Address, City,


PostalCode, Country)
VALUES (‘Yap Jason’, ‘Karl Matthew’, ‘Kentucky’,
‘Walla’, ‘01-012’, ‘Poland');
Insert Data Only in Specified Columns
 SQL statement that will insert a new record, but only insert data
in the "CustomerName", "City", and "Country" columns
(CustomerID will be updated automatically)

INSERT INTO Customers (CustomerName, City, Country)


VALUES ('Cardinal', 'Stavanger', 'Norway');
ACTIVITY 10
Insert a new record in the Customers table for
the following columns
CustomerName, Address, City,
PostalCode,Country
With the following data
Jes Nazer, Gate 18, Sandnes, 4306, Norway
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;
 The following SQL statement updates the first customer (CustomerID = 1)
with a new contact person and a new city.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt’
WHERE CustomerID = 1;
UPDATE Multiple Records
It is the WHERE clause that determines how many records that
will be updated.
 The following SQL statement will update the contactname to
"Juan" for all records where country is "Mexico":
UPDATE Customers
SET ContactName='Juan’
WHERE Country='Mexico’;
Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL
records will be updated!
The SQL DELETE Statement

 The DELETE statement is used to delete existing records in


a table.
DELETE FROM table_name WHERE condition;
SQL Constraints
 SQL constraints are used to specify rules for data in a table.
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.
Syntax
 CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
SQL 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 - Uniquely identifies a row/record in another table
 CHECK - Ensures that all values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column when no value is specified
 INDEX - Used to create and retrieve data from the database very quickly

You might also like