Sunteți pe pagina 1din 7

A Guide to Standard SQL

Starting up MySQL

Start up the Terminal application.

Type mysql u root p

If there is one, you will be prompted for a password.

Creating a Database
To see databases that are already available type SHOW DATABASES;
To create a database type CREATE DATABASE <database name>;
To make the database current, type USE <database name>;
To see what tables have been created in your database, type SHOW TABLES;
To view table setup type DESCRIBE <table name>;
DDL Data Definition Language
A data definition language is a standard set of instructions used to create and relate
data tables in a relational database.
In SQL, the standard parts of a data definition are:
CREATE TABLE table_name ();
the main command which starts the whole process; the rest of the definition is
contained within the brackets.
The names of the fields then follow with their data types. Conventionally, key words
are written in capitals and table and field names in mixed case. In SQL data types are
similar but not the same as those you are used to in defining a data table:
Text:

The two main text types are CHAR(length) a text field of fixed
length and VARCHAR(length) a variable length field up to a
maximum size. Use VARCHAR unless you have particular reason
otherwise.

Number

INTEGER
REAL

Date/time

DATE
TIME

Logical

BOOLEAN

PRIMARY KEY
The primary key is added by including the PRIMARY KET command. This is done in
different ways according to the implementation of SQL.
1. By adding the keywords PRIMARY KEY after the field definition.
e.g. Cust_ID INTEGER PRIMARY KEY
2. Or by adding the keywords PRIMARY KEY at the end of the table definition
followed by the key fields in brackets.
e.g. Cust_ID INTEGER

PRIMARY KEY(Cust_ID)
Primary keys cannot be empty so it is common practice to define these fields by
including the keywords NOT NULL. This can be applied to all fields of course to
ensure data entry.
FOREIGN KEY
A foreign key is defining by specifying which field is being used then using the key
word REFERENCES to indicate which primary key it is related to.
e.g. CREATE TABLE Customers (
Cust_ID INTEGER NOT NULL,
SURNAME VARCHAR(20),

PRIMARY KEY (Cust_ID));
CREATE TABLE Orders (
OrderNum VARCHAR(12) NOT NULL,
Customer INTEGER NOT NULL,
OrderDate DATE,

PRIMARY KEY (OrderNum)
FOREIGN KEY (Customer) REFERENCES Customer(Cust_ID));

Managing your database and tables


If you want to get rid of bits that youve made accidentally or tidy up there are a
number of commands you can use:
DROP DATABASE <Database Name> deletes the entire database
DROP TABLE <Table Name>

deletes a table

TRUNCATE TABLE <Table Name>

removes all the data in a table

If youve made a mistake in the way youve set up a table you can use the ALTER
TABLE command to add, delete or alter fields:
ALTER TABLE <Table Name>
ADD <Field Name> <Data Type>

adds another field to the table

ALTER TABLE <Table Name>


DROP COLUMN <Field Name>

deletes a field

ALTER TABLE <Table Name>


MODIFY COLUMN <Field Name> <Data Type>

changes the field to the


specified data type

ALTER TABLE <Table Name>


ADD PRIMARY KEY(<Field Name>) to specify a primary key after setup
ALTER TABLE <Table Name>
DROP PRIMARY KEY

removes the primary key

An Example
To define the tables required in a system to store details about invoices to be sent to
clients these might well appear as follows:
CREATE TABLE Customer(
Cust_ID INTEGER NOT NULL,
Name VARCHAR(20),
Address VARCHAR(50),
Credit BOOLEAN,
PRIMARY KEY(Cust_ID));

CREATE TABLE Product(


ProductCode CHAR(8) NOT
NULL,
Description VARCHAR(50),
Price REAL,
QuInStock INTEGER,
PRIMARY KEY(ProductCode));

CREATE TABLE Order(


OrderNum INTEGER NOT NULL,
Customer INTEGER NOT NULL,
OrderDate DATE,
PRIMARY KEY (OrderNum),
FOREIGN KEY (Customer) REFERENCES Customer(Cust_ID));
CREATE TABLE OrderLine(
OrderNum INTEGER NOT NULL,
Product CHAR(8) NOT NULL,
Quantity INTEGER,
PRIMARY KEY(OrderNum,Product),
FOREIGN KEY (OrderNum) REFERENCES Order(OrderNum),
FOREIGN KEY (Product) REFERENCES Product(ProductCode));

DML Data Manipulation Language


Extracting Data
This is the kind of language you are probably more used to. DML is the language
used to extract data from a database by linking tables, filtering using criteria, sorting
into order; in short this is how queries are created.
The four standard key words in an SQL selection query are:
SELECT

specifies which fields are to be displayed. It is convention to show


the table name then a full stop then the field name e.g.
Customer.CustID. This prevents problems (especially with
foreign keys) if two tables have fields with the same name in them.
However providing that field names are unique, the table name
doesnt have to be specified.

FROM

specifies the tables from which fields are to be extracted.

WHERE

specifies the criteria which filter out specific records. If you are
using more than one table you must include a WHERE clause that
shows which fields are connected e.g.
WHERE Order.Cust = Customer.ID.

ORDER BY

indicates which fields are used to sort data. These are read from left
to right so the data is sorted on the first field listed then, where
values are the same in the first field, these are sorted by he second
field and so on. For example ORDER BY Surname,DOB would
sort by surname then if two people share the same surname they are
sorted by date of birth. Sorting is always in ascending order unless
the keyword DESC is added at the end.

An Example
The following query would locate all students who have taken a Maths exam and list
them showing the highest mark first. Students who have the same exam mark are
shown in surname order.
SELECT Surname, Forename, Exam.Date, Mark, PassMark
FROM Student, Exam
WHERE Student.ID=Exam.StID AND Exam.Subject=Maths
ORDER BY Mark DESC,Surname

Summarising Data
There are a number of different functions that can be used to aggregate data. The most
common are: SUM(), AVG(), MAX(),MIN(), COUNT(). These functions are
included in the SELECT part of the query.
So for example an order table may contain:
O_Id
1
2
3
4
5
6

OrderDate
2008/11/12
2008/10/23
2008/11/12
2008/09/03
2008/08/30
2008/10/23

OrderPrice
1000
1600
700
300
2000
100

Customer
Hansen
Nilsen
Hansen
Hansen
Jensen
Nilsen

To aggregate the order values for each customer we could write a SQL query:
SELECT Customer,OrderDate,SUM(OrderPrice)
FROM Orders
ORDER BY Customer
Unfortunately this would sum the whole table then list this sum for each row:
Customer
Hansen
Hansen
Hansen
Jensen
Nilsen
Nilsen

OrderDate
2008/11/12
2008/11/12
2008/09/03
2008/08/30
2008/10/23
2008/10/23

SUM(OrderPrice
5700
5700
5700
5700
5700
5700

To make the query produce more useful results we use the GROUP BY keywords.
This groups by every unique combination of the fields specified.
So we could create this query

to get these results:

SELECT Customer,OrderDate,SUM(OrderPrice)

Customer
Hansen
Hansen
Jensen
Nilsen

FROM Orders
GROUP BY Customer,OrderDate
or the query
SELECT Customer,SUM(OrderPrice)
FROM Orders
GROUP BY Customer

OrderDate
2008/11/12
2008/09/03
2008/08/30
2008/10/23

SUM(OrderPrice
1700
300
2000
1700

to produce:
Customer SUM(OrderPrice
Hansen
2000
Jensen
2000
Nilsen
1700

Changing the Contents of the Database


So far we have only dealt with how to view the data in the database. SQL also allows
you to change what is there through three main operations:

Insertion

Deletion

Updating

Inserting Records
To add a new record into a SQL database you use the INSERT INTO keywords.
INSERT INTO specify to which table the record is to be added and which fields
data is being inserted;
VALUES

the new values that are to be inserted in the fields specified above.

So to add a new record for Fred Brown aged 12 into the Students table you would
enter:
INSERT INTO Students (Forename, Surname, Age)
VALUES (Fred, Brown, 12);
You can also use a SELECT query to provide the values to be inserted. This will
insert a number of rows at the same time. This query will take all the records from a
Loans table and add them to the Overdues table if their BorrowedDate is overdue.
INSERT INTO Overdues (BorrowerID, BorrowedDate)
SELECT BorrowerID,BorrowedDate FROM Loans WHERE
BorrowedDate < Today-21;
Deleting Records
Deleting records is done using the DELETE FROM key words. A similar structure to
the WHERE clause in a SELECT query is used to decide which records should be
deleted.
DELETE FROM determines which table records are to be deleted from;
WHERE

specifies which records are to be deleted.

This query will delete all students whose score is below 50.
DELETE FROM Students WHERE Score <50;

Updating Records
There are three parts to an UPDATE:
UPDATE

name of the table to update

SET

indicates which fields are to be updated with what

WHERE

a Boolean statement which determines which records are to be updated.


Be careful here because this part is optional and leaving it off will lead
to every record being updated.

The following SQL statement will change the address of a specific customer
UPDATE Customers
SET CustomerAddress=12 High St, Welcombe,
CustomerPostCode= FG5 8HG
WHERE Cust_ID=002FG7;

S-ar putea să vă placă și