0% found this document useful (0 votes)
6 views

A Bit of SQL

Uploaded by

fatima.s9786
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

A Bit of SQL

Uploaded by

fatima.s9786
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

SQL Matthew Rowe

A bit of SQL
Using Access

Use this document to familiarize yourself with SQL and


the process of forming and saving queries. Make
mistakes – that’s how you learn. It doesn’t matter at this
stage.

Matthew Rowe
5 January 2012
Contents
1. SQL – A quick introduction............................................................................................................2
1.1. The structure of SQL e.g. DML, DDL and DCL.........................................................................4
1.1.1. DDL................................................................................................................................4
1.1.2. DML................................................................................................................................5
1.1.3. SQL.................................................................................................................................7
1.1.4. DDL (One more example)...............................................................................................7
1.1.5. Constraints.....................................................................................................................8
1.1.6. DCL (Not covered but here’s an example)...................................................................10
1.1.7. DCL 1............................................................................................................................11
1.1.8. DCL 2............................................................................................................................11
1.2. The use of SQL by database administrators, users and application developers...................12
1.3. A series of suitable SQL scripts for the system (including queries using more than one table
and queries using Boolean expressions) with an explanation of their structure.............................13

Page 1 of 14
1. SQL – A quick introduction.
SQL (Structured Query Language or Sequel) is the language used to manipulate databases (DB).

ANSI SQL is the standard format of the language, however, DB manufactures often debase the
standard language to suit their needs.

Therefore when writing SQL using Access, the notation looks slightly different, however the overall
structure remains essentially the same.

Start Access and create a blank database.

We won’t need the default table so right click “Table1” tab and select “Close”.

Page 2 of 14
We are now going to open the SQL window to enable us to write SQL queries to create and
manipulate tables (virtually independently of the Access Front End).

Click, Create. Then click Query Design.

Close the “Show Table” dialog box.

Select View/SQL View.

We are now in a position to add the SQL code.

 Hot tip: It is worth noting that you can access the SQL view at any point, so if you’ve created a
regular Query using Design View or the Wizard, you can see how the SQL looks by selecting the
query and then choosing View/SQL View.

 Note: Access does not write very pretty SQL, it uses Inner Joins and every column is given an alias
which is unnecessary. Please use your skills to unpick what’s necessary and what isn’t when you
look at SQL generated by Access.

Page 3 of 14
1.1. The structure of SQL e.g. DML, DDL and DCL

SQL is the overall term for the language we type to manipulate data in a database, it is subdivided in
to DML (data manipulation language), DDL (data definition language) and DCL (data control
language).

Action: Try these examples – IN ORDER! You’ll need to run each query and save it with the
filename given.

1.1.1. DDL

This is an example of a DDL query (CREATE)


This query creates a table called “EMP”, with 3 fields, EmpNo (a primary key) set as a Number Field,
FName set as a text field and LName set as a text field.

When you’ve typed it in, save this as DDL_CREATE

CREATE TABLE EMP (


EmpNo Number primary key,
FName text,
LName text);

Note: Run this query, then look at your tables, you should now see a new table called EMP.
 Critical: You can’t run this twice! The table already exists, doing so will result in an error.

Page 4 of 14
Oops! Forgot to add a field.

Luckily SQL allows us to alter tables after they’ve


been built.

(Actually SQL allows us to do anything we want to


tables)

We will now alter this table.

This is an example of a DDL query (ALTER)

Create it in the same way you did before and save it as DDL_ALTER

ALTER TABLE EMP


ADD
PENSION bit,
DEPTNO NUMBER;

Note: This adds two columns, one is a BIT datatype, it only stores 0 or -1, otherwise known as
TRUE/FALSE or Boolean, the second column it adds is the DEPTNO, which we could use as a foreign
key. Look at your EMP table now.

1.1.2. DML

This is an example of a DML query (INSERT)

Save this as DML_INSERT1

INSERT INTO EMP


VALUES (1, "John",”Smith”,0, 12);

Note: This adds a record to the EMP table. John Smith, is employee number 1, he has NO
pension and works in DeptNo 12.

This is another example of a DML query (INSERT)

Try another, save this as DML_INSERT2

INSERT INTO EMP


VALUES (2, "Manjit",”Kwarteng”,-1, 3);

Page 5 of 14
Note: This adds a record to the EMP table. Manjit Kwarteng, is employee number 2, she has GOT
A pension and works in DeptNo 3.

Look at your queries, if they are done right you will see a different icon, next to these two with a
PLUS sign. Look in your EMP table, can you see your two new records.

This is an example of a DML query (UPDATE)

Save this as DML_UPDATE

UPDATE EMP
SET FNAME = "Jimmy"
WHERE EMPNO=2;

Note: This alters Manjits record to read Jimmy Kwarteng.


Again, look at your queries and note the different icon, look at your table and read the newly
updated record.

This is an example of a DML query (DELETE)

Save this as DML_DELETE

DELETE * FROM EMP


WHERE EMPNO=1;

Note: This deletes JOHN’S record from your database.


Also Note: DML also includes SELECT, when you type a SELCT statement you are writing DML

Page 6 of 14
1.1.3. SQL

Now lets have some fun with it.

SQL does lots of clever things, try this.

Add 10 records (manually) into your EMP table, make sure that you have different first names.

Then type this query.

Save this as SQL_TOP3

SELECT TOP 3 FNAME, EMPNO


FROM EMP
WHERE EMPNO<=10
ORDER BY FNAME DESC;

Note: This sorts your FNAME column into alphabetical order and shows you the BOTTOM 3
records, remove the DESC to see the TOP 3!

There are lots of features like this, simply use ACCESS help to find features.

1.1.4. DDL (One more example)

This is an example of a DDL query (DROP) guess what it does:-

 Critical: Do NOT RUN THIS QUERY, if you do you will have to re-run you previous queries
and re-insert your data!!!

Save this as DDL_DROP

DROP TABLE EMP;

Page 7 of 14
1.1.5. Constraints

You can constrain a database table in many ways. A constraint is a restriction, your parents probably
constrain you in certain ways:

 Call me at 10:00
 Don’t talk to strangers
 You can’t leave the table until you’ve cleared your plate.
 Etc…

In the same way we can add constraints to a database table, we can ensure that no value over 200
goes into a number field or, more commonly, we can use constraints to ENFORCE REFERENTIAL
INTEGRITY.

Here we will build a new table “PayCheques” with a forced link to the EMP table.

Key in the following query.

CREATE TABLE PayCheques


(ChequeID INTEGER CONSTRAINT PK_ChequeID PRIMARY KEY,
EMPNO NUMBER NOT NULL CONSTRAINT FK_EMPNO
REFERENCES EMP (EMPNO),
DatePaid DATETIME,
Amount CURRENCY);

Let’s examine this…

ChequeID INTEGER CONSTRAINT PK_ChequeID PRIMARY KEY,


Here we create a primary key but we give the constraint/rule a name “ChequeID” (you now have the
option to drop it if you feel it’s no longer necessary).

EMPNO NUMBER NOT NULL CONSTRAINT FK_EMPNO


REFERENCES EMP (EMPNO),

This is a slightly different constraint firstly it forces NOT NULL (so every record must have related
EMPNO). Then we link it to the relevant table using “References”.

Check your relationships window to ensure this has worked.

Page 8 of 14
Let’s make it harder

We know that we want to link our EMP table to another table which will show what Department the
employees work in (we created the Foreign Key).

So let’s create the table and add the constraint.

Create the table first.


CREATE TABLE Departments
(DeptID NUMBER CONSTRAINT PK_DeptID PRIMARY KEY,
DeptName TEXT,
RoomNumber Text);

Now we’ll add the constraint (or link).

Note: This constraint is added to the EMP table as the relationship goes in this direction (1
employee works in 1 department).

ALTER TABLE EMP


ALTER COLUMN DEPTNO Number NOT NULL CONSTRAINT FK_DeptNo
References Departments (DeptID);

Why doesn’t it work???

Read the error message and try to figure it out.

Once it works, revisit the relationships window and see if all the relationships are where you’d
expect them to be.

Page 9 of 14
1.1.6. DCL (Not covered but here’s an example)

You have created a single user database – that means that only a single user (you) have access to it.

Therefore DCL is not relevant for your databases.

However, consider this –

A company consists of many people working in different departments.

Here is a company diagram for MAXIMO.

Every user has a database account. Users can be given different levels of access to tables.
1. Completely denied
2. Read only
3. Read and Write
4. Read, Write, Alter

The people in Procurement Management are in a GROUP called Procurement. As a database


administrator you can GRANT access to a table or set of tables that the people in that department
need to see. It’s quicker to GRANT access to GROUPS of people, rather than doing this on a one to
one basis.

You can also REVOKE privileges for GROUPS or INDIVIDUALS.

Page 10 of 14
The code used, is as follows.

1.1.7. DCL 1

GRANT select, insert ON EMP TO PROCGROUP ;

This allows (GRANTS) all users in the PROCGROUP to SELECT and INSERT
data to the EMP table.

If you want to take privileges away from a group of users you could use this code.

1.1.8. DCL 2

REVOKE DELETE ON EMP FROM anderson;

This stops ANDERSON from deleting data on the EMP table.

To stop everyone in the PROCGROUP doing this we would use this.

REVOKE DELETE ON EMP FROM PROCGROUP;

 Easy so far?

 Cartesian Products! 


Please remember that when dealing with more than one table you MUST state how you’re your
tables are linked.

Take the following example.

EMP DEPT
EmpNo (PK) DeptNo (PK)
FName DeptName
LName TelephoneNo
Pension ManagerNo
DeptNo (FK)

EMP has 100 records


DEPT has 10 records

Page 11 of 14
 The following query is WRONG!
Select EmpNo, FName, DeptName
From EMP, DEPT
Where FNAME=”John” ;

This will produce 100x10 (1000) records all containing all of the details and substituting the FNAME
field for John. (Something like this…)

EmpNo FName DeptName


1 John Works
2 John IT
3 John Front Desk
4 John Canteen

This is a Cartesian product! Although you know how your tables are linked, the database doesn’t.
Therefore you MUST tell it.

 The following query is CORRECT!


Select EmpNo, FName, DeptName
From EMP, DEPT
Where FNAME=”John” and EMP.DEPTNo = DEPT.DeptNo ;

Notice the table name before the key, this is there because both tables have a field called DEPTNo,
the table name tells SQL which table to select from!!

1.2. The use of SQL by database administrators, users and


application developers.

Now you’ve seen a few queries work, how easy is it to recreate the table EMP table, using your
saved queries?

Easy!
Q: -Why do we use SQL rather than design view?

A: -Because SQL is more powerful and SQL is common in all databases. With SQL you can program in
Oracle, Access, Informix etc… Using Access Design view restricts you to working with Access.

Write briefly about the benefits of SQL scripts for administrators (about 1 page).

Page 12 of 14
1.3. A series of suitable SQL scripts for the system (including
queries using more than one table and queries using
Boolean expressions) with an explanation of their structure.

Now it’s down to you.

See if you can create a database consisting of two tables using SQL formed constraints.

The two tables should contain details of your friends and the car they drive.

Consider
 What is a good PK for a car table?
 Can a friend own more than one car?
 Use a Boolean expression to show if they should get a birthday card from you or not.

Remember: You need to use a BOOLEAN expression, so you will need one field in your database
saved as a BIT! Use a table where you don’t have much data, use your imagination when deciding
what to call the field. You could use an SQL ALTER query to add this field.

When you select you can use TRUE to pull out any records stored as -1.

Like this:-

SELECT * from EMP where PENSION=TRUE;

This selects all fields from the EMP table where the EMPLOYEE has a PENSION
(-1).

Try it using FALSE to pull out the zeros.

 Good Luck! 

Page 13 of 14

You might also like