Sie sind auf Seite 1von 8

Tutorial on SQL*

INLS 461-002 Fall 2010, Instructor: Xi Niu School of Information and Library Science, UNC at Chapel Hill Nov 10, 2010

Goals:
1. Help you learn SQL 2. Practical knowledge about using SQL in MS Access database

SQL Structured Query Language 1. What is SQL?


At its simplest, it is the language that is used to extract, manipulate, and structure data that resides in a relational database management system (RDBMS). In other words, to get an answer from your database, you must ask the question in SQL. Standard query language for commercial relational DBMSs.

2. Why and where use SQL?


Although Access is graphic user interface, actually for every request you make, Access converts it to SQL under the covers. In addition to queries, SQL is used to create database schema, create tables, populate tables, build forms and reports SQL is prevalent. Thus, understanding it will greatly increase your ability to take control of all the programming power that Access gives you.

3. Main functions of SQL


1. 2. 3. Data Definition Language (DDL) Create tables Insert/delete/update operations Views/Assertions/Triggers

NOTE: DDL only takes care of creating structures, but not the data itself.


*The data comes from Dr. Hemmingers Database course (INLS 623)

1. 2. 3.

Data Manipulation Language (DML) Basic Queries in SQL Complex SQL Queries Set Operations

NOTE: DML only takes care of manipulating the data, but has no effect on the structure of the data.

4. Use DDL
4.1 Creating and deleting tables

CREATE TABLE flights( flno INTEGER CONSTRAINT pk_flights PRIMARY KEY, origin TEXT(20), destination TEXT(30), distance INTEGER, departs DATETIME, arrives DATETIME, price SINGLE );


NOTE: If you do not declare a length for text fields, they will default to 255 characters. For consistency and code readability, you should always define your field lengths. You can declare a field to be NOT NULL, which means that null values cannot be inserted into that particular field; a value is always required. A null value should not be confused with an empty string or a value of 0, it is simply the database representation of an unknown value. CREATE TABLE flights( flno INTEGER CONSTRAINT pk_flights PRIMARY KEY, origin TEXT(20) NOT NULL, destination TEXT(30) NOT NULL, distance INTEGER, departs DATETIME, arrives DATETIME, price SINGLE ); Populate the table (strictly speaking, this is data manipulation rather than data defination)

INSERT INTO flights VALUES (99,"Los Angeles","Washington D.C.",2308,'2005/04/12 09:30','2005/04/12 21:40',235.98);

4.2 Remove a table from the database

DROP TABLE flights;


4.3. Defining Relationships Between Tables

CREATE TABLE aircraft( aid INTEGER CONSTRAINT pk_aircraft PRIMARY KEY, aname TEXT(30), cruisingrange INTEGER ); CREATE TABLE employees( eid INTEGER CONSTRAINT pk_employees PRIMARY KEY, ename TEXT(30), salary INTEGER ); CREATE TABLE certified( eid INTEGER CONSTRAINT fk_eid REFERENCES employee (eid), aid INTEGER CONSTRAINT fk_aid REFERENCES aircraft (aid), CONSTRAINT pk_certified PRIMARY KEY (eid,aid) );

ER Model of these tables

5. Use DML
Summary: SELECT FROM WHERE GORUP BY HAVING ORDER BY 5.1 Retrieving records * find flight number and distance SELECT flno, distance FROM flights; * find distance information displayed as cruising range

SELECT distance AS [cruising range] FROM flights; * find flight records whose destination is New York SELECT * FROM flights WHERE destination = "New York";

*find flight records whose origin is Chicago and destination is New York

SELECT * FROM flights WHERE origin = "Chicago" AND destination = "New York";

* find flight number whose price is greater than 250 SELECT flno FROM flights WHERE price > 250;

* find flight number whose origin starts with M SELECT flno, origin FROM flights WHERE origin LIKE "M*";

Common wildcards Wildcard character * % # [abcd] [!abcd] 5.2 Sorting the result set * order the flight records by descending price order Description Zero or more characters Any single character Any single digit Any single character in list Any single character not in list

SELECT flno, distance FROM flights ORDER BY price DESC; 5.3 Using aggregate functions * find the count of flights whose origin is Madison

SELECT count(*) FROM flights WHERE origin = "Madison";

* find the average price for the flights whose designation is New York SELECT avg(price) FROM flights WHERE destination = "New York";

* find the minimum and maximum distances of flights SELECT min(distance), max(distance) FROM flights; 5.4 Groping records in a result set * find the average price for flights respectively for different destinations.

SELECT avg(price) FROM flights GROUP BY destination; * find the average price if it is above 250 for flights respectively for different destinations. SELECT avg(price) FROM flights GROUP BY destination HAVING avg(price)>250;

5.5 Updating records in a table * change the price of #99 flight to 300. UPDATE flights SET price = 300 WHERE flno = 99;

5.6 Deleting records in a table * delete records whose distance is 5478 DELETE FROM flights WHERE distance = 5478; * delete all records from flights DELETE FROM flights;

6. More SQL querying


summary: JOIN, IN, UNION, Concept of set, nested query 6.1 Find the names of aircraft such that all pilots certified to operate them earn more than 8000.

SELECT DISTINCT a.aname FROM certified c,employees e,aircraft a WHERE c.eid = e.eid AND c.aid = a.aid AND e.salary > 8000;

6.2. For each pilot who is certified for more than three aircraft, find the eid and the maximum cruisingrange of the aircraft that he or she is certified for. SELECT e.eid,max(a.cruisingrange) FROM certified c,employees e,aircraft a WHERE c.eid = e.eid AND c.aid = a.aid AND e.eid IN (SELECT c.eid FROM certified c GROUP BY c.eid HAVING count(c.aid)>3) GROUP BY e.eid;

6.3. Find the names of pilots whose salary is less than the price of the cheapest route from Los Angeles to Honolulu. SELECT ename FROM employees WHERE salary < ( SELECT min(price) FROM flights WHERE origin = "Los Angeles" AND destination = "Honolulu"); 6.4. For all aircraft with cruisingrange over 1,000 miles, find the name of the aircraft and the average salary of all pilots certified for this aircraft. SELECT a.aname,avg(salary) FROM certified c,employees e,aircraft a WHERE c.eid = e.eid AND c.aid = a.aid AND a.cruisingrange > 1000 GROUP BY a.aname;

6.5. Find the names of pilots certified for some Boeing aircraft. SELECT DISTINCT e.ename FROM certified c,employees e,aircraft a WHERE c.eid = e.eid AND c.aid = a.aid AND a.aname LIKE "Boeing*";

6.6. A customer wants to travel from Madison to New York with no more than one change of flight. List the choice of departure times from Madison if the customer wants to arrive in New York by 6 p.m. ? In-class exercise

8. SQL coding conventions


The idea is to display the code in such a way as to make it easy to read and understand. This is accomplished by using a mix of white space, new lines, and uppercase keywords. In general, use uppercase for all SQL keywords, and if you mush break the line of SQL code, try to do so with a major section of the SQL statement. Poorly formatted SQL code Create table student( snum integer constraint pk_student primary key, sname text(30) not null, major text(25) not null, standing text(2),age integer);


Well-formatted SQL code CREATE TABLE student( snum INTEGER CONSTRAINT pk_student PRIMARY KEY, sname TEXT(30) NOT NULL, major TEXT(25) NOT NULL, standing TEXT(2), age INTEGER );

Das könnte Ihnen auch gefallen