Introduction to Microsoft Jet SQL



Similar documents
Information Systems SQL. Nikolaj Popov

Mini User's Guide for SQL*Plus T. J. Teorey

Oracle SQL. Course Summary. Duration. Objectives

SQL. Short introduction

Database Query 1: SQL Basics

Oracle Database: SQL and PL/SQL Fundamentals

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Oracle Database: SQL and PL/SQL Fundamentals NEW

LABSHEET 1: creating a table, primary keys and data types

A Comparison of Database Query Languages: SQL, SPARQL, CQL, DMX

Oracle Database: SQL and PL/SQL Fundamentals

Access Queries (Office 2003)

Boats bid bname color 101 Interlake blue 102 Interlake red 103 Clipper green 104 Marine red. Figure 1: Instances of Sailors, Boats and Reserves

Financial Data Access with SQL, Excel & VBA

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Relational Database: Additional Operations on Relations; SQL

Oracle Database 12c: Introduction to SQL Ed 1.1

How To Create A Table In Sql (Ahem)

3.GETTING STARTED WITH ORACLE8i

Programming with SQL

Chapter 5. SQL: Queries, Constraints, Triggers

Oracle Database 10g: Introduction to SQL

Microsoft Access 3: Understanding and Creating Queries

1. SELECT DISTINCT f.fname FROM Faculty f, Class c WHERE f.fid = c.fid AND c.room = LWSN1106

SQL SELECT Query: Intermediate

Database Applications Microsoft Access

SQL Basics. Introduction to Standard Query Language

A Brief Introduction to MySQL

David M. Kroenke and David J. Auer Database Processing: Fundamentals, Design and Implementation

Advanced Query for Query Developers

Netezza SQL Class Outline

Instant SQL Programming

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Database Administration with MySQL

Oracle 10g PL/SQL Training

Click to create a query in Design View. and click the Query Design button in the Queries group to create a new table in Design View.

Oracle Database: Introduction to SQL

P_Id LastName FirstName Address City 1 Kumari Mounitha VPura Bangalore 2 Kumar Pranav Yelhanka Bangalore 3 Gubbi Sharan Hebbal Tumkur

Oracle Database 11g SQL

Databases in Engineering / Lab-1 (MS-Access/SQL)

Using AND in a Query: Step 1: Open Query Design

Using Multiple Operations. Implementing Table Operations Using Structured Query Language (SQL)

Oracle Database: Introduction to SQL

SQL Server 2008 Core Skills. Gary Young 2011

Structured Query Language (SQL)

MOC 20461C: Querying Microsoft SQL Server. Course Overview

Creating QBE Queries in Microsoft SQL Server

IT2305 Database Systems I (Compulsory)

Performing Queries Using PROC SQL (1)

Example Instances. SQL: Queries, Programming, Triggers. Conceptual Evaluation Strategy. Basic SQL Query. A Note on Range Variables

SQL: Queries, Programming, Triggers

Relational Algebra. Query Languages Review. Operators. Select (σ), Project (π), Union ( ), Difference (-), Join: Natural (*) and Theta ( )

More on SQL. Juliana Freire. Some slides adapted from J. Ullman, L. Delcambre, R. Ramakrishnan, G. Lindstrom and Silberschatz, Korth and Sudarshan

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

2. Basic Relational Data Model

Database Migration from MySQL to RDM Server

Chapter 5. Microsoft Access

Oracle Database: Introduction to SQL

SQL: Queries, Programming, Triggers

Unit 10: Microsoft Access Queries

IT2304: Database Systems 1 (DBS 1)

A basic create statement for a simple student table would look like the following.

Access 2010: Creating Queries Table of Contents INTRODUCTION TO QUERIES... 2 QUERY JOINS... 2 INNER JOINS... 3 OUTER JOINS...


SQL Server An Overview

Overview of Database Management Systems

SQL Server Database Coding Standards and Guidelines

CSC 443 Data Base Management Systems. Basic SQL

MS Access Lab 2. Topic: Tables

Information and Computer Science Department ICS 324 Database Systems Lab#11 SQL-Basic Query

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

Objectives of SQL. Terminology for Relational Model. Introduction to SQL

History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG)

ICAB4136B Use structured query language to create database structures and manipulate data

Introduction to SQL and SQL in R. LISA Short Courses Xinran Hu

Chapter 1 Overview of the SQL Procedure

Utility Software II lab 1 Jacek Wiślicki, jacenty@kis.p.lodz.pl original material by Hubert Kołodziejski

SQL Programming. Student Workbook

T-SQL STANDARD ELEMENTS

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

Handling Missing Values in the SQL Procedure

Oracle Database: SQL and PL/SQL Fundamentals NEW

Section of DBMS Selection & Evaluation Questionnaire

Lab Manual. Databases. Microsoft Access. Peeking into Computer Science Access Lab manual

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

Advance DBMS. Structured Query Language (SQL)

4. The Third Stage In Designing A Database Is When We Analyze Our Tables More Closely And Create A Between Tables

4. SQL. Contents. Example Database. CUSTOMERS(FName, LName, CAddress, Account) PRODUCTS(Prodname, Category) SUPPLIERS(SName, SAddress, Chain)

Microsoft Access Lesson 5: Structured Query Language (SQL)

SUBQUERIES AND VIEWS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 6

MS Access: Advanced Tables and Queries. Lesson Notes Author: Pamela Schmidt

Sample- for evaluation only. Introductory Access. TeachUcomp, Inc. A Presentation of TeachUcomp Incorporated. Copyright TeachUcomp, Inc.

Elena Baralis, Silvia Chiusano Politecnico di Torino. Pag. 1. Active database systems. Triggers. Triggers. Active database systems.

Data Tool Platform SQL Development Tools

Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro

Transcription:

Introduction to Microsoft Jet SQL Microsoft Jet SQL is a relational database language based on the SQL 1989 standard of the American Standards Institute (ANSI). Microsoft Jet SQL contains two kinds of statements: Data Definition Language (DDL) statements. These statements let you define and modify the schema of your database. Data Manipulation Language (DML) statements. These statements let you create, access and modify data in your database. Statement CREATE TABLE DROP TABLE ALTER TABLE CREATE INDEX DROP INDEX Table 1 Some DDL statements Description Defines a table in a database Deletes a table from a database Modifies a table in a database Adds an index to a table Deletes an index from a table Statement SELECT INSERT INTO UPDATE DELETE FROM UNION Table 2. Some DML statements Description Retrieves and displays one or more rows from a table. Adds new rows to a table Changes column values in one or more rows of a table Deletes one or more rows from a table Combines two or more SELECT statements to create a complex query 1

Data Definition Language Creating Tables The CREATE TABLE statement creates a new, empty table with the columns that you specify. Here is an example that creates a table named sp: CREATE TABLE SP ( SNUM TEXT NOT NULL, PNUM TEXT NOT NULL, QTY SHORT NOT NULL, CONSTRAINT one PRIMARY KEY (SNUM,PNUM), CONSTRAINT two FOREIGN KEY (SNUM) REFERENCES S (SNUM), CONSTRAINT three FOREIGN KEY (PNUM) REFERENCES P (PNUM)); The table SP has three columns; SNUM, PNUM, and QTY. For each column you name, you must enter a data type for that column. To indicate that the column must have a value, use the optional keyword NOT NULL. The CONSTRAINT instruction can be used to specify primary keys, foreign keys, and candidate keys. To specify that a column is a candidate key, use the keyword UNIQUE. A CREATE TABLE statement can contain zero or more CONSTRAINT instructions ( a primary key is therefore not necessary to specify! ). For every key that is specified, an index is automatically created. Deleting Tables The DROP TABLE statement deletes a table from the database. It also deletes all indexes defined on that table, and all data associated with the table. The following example deletes the table SUPPLIERS: DROP TABLE SUPPLIERS; Altering Tables The ALTER TABLE statement lets you add new columns to a table or delete columns from a table. To add a new column DISCOUNT to the SUPPLIERS table you write: 2

ALTER TABLE SUPPLIERS ADD COLUMN DISCOUNT SINGLE; To delete the same column you write: ALTER TABLE SUPPLIERS DROP COLUMN DISCOUNT; Creating Indexes The CREATE INDEX statement creates an index on one or more columns. The following example creates an index XCITY on SUPPLIERS. CREATE INDEX XCITY on SUPPLIERS (CITY); Deleting Indexes The DROP INDEX statement deletes one or more indexes from the database. To delete the index XCITY write: DROP INDEX XCITY; Data Types Table 3 lists some of the data types that SQL supports. SQL Data Type Size Description BINARY Data of this type is stored in binary, i. e. no conversion is done BYTE 1 byte Integer between 0 and 255 COUNTER 4 bytes A number that is automatically incremented when a new record is inserted CURRENCY 8 bytes Values between 922 337 203 685 477,5808 and 922 337 203 685 477,5807 DATETIME 8 bytes Date or time (years 100 9999) SINGLE 4 bytes Decimal number with single precision DOUBLE 8 bytes Decimal number with double precision SHORT 2 bytes Integer between 32 768 and 32 767 LONG 4 bytes Integer between 2 147 483 648 and 2 147483647 LONGTEXT 1 byte/char Between 0 and 1,2 GB LONGBINARY Between 0 and 1,2 GB TEXT 1 byte/char Up to 255 characters Table 3. Microsoft Jet SQL Data Types 3

Some Words on Syntax Each Microsoft Jet SQL statement must end with a semicolon. Any number of spaces, tabs, and newline characters are treated as a single space. When you use the same column name in more than one table and those columns are referenced in the same query, you must qualify the column names with their table names (e.g. suppliers.city and parts.city in the suppliers and parts database). A character string or a date must be enclosed in either single or double quotation marks. There exist two wildcard characters that can be used in LIKE clauses to match character strings. The asterisk character (*) matches zero or more characters. The question mark character (?) matches any single character. Data Manipulation Language Inserting Rows The INSERT INTO statement inserts one or more rows into an existing table. The data you insert can be a list of values that you supply or values from another table. Add a new part record to PARTS. (By including the field list, the color field can be omitted) INSERT INTO PARTS( P_NUM, CITY, WEIGHT) VALUES( P7, Athens, 24); Add a new record to PARTS (By omitting the field list, all values must be present) INSERT INTO PARTS VALUES( P8, Sprocket, pink, 14, Nice ); Add those suppliers who have a status greater than 15 to a table HIGH_STATUS (Multirow insert). INSERT INTO HIGH_STATUS (S_NUM, SNAME, STATUS, CITY) SELECT * FROM SUPPLIERS WHERE STATUS > 15; 4

Updating Rows The UPDATE statement changes column values in one or more rows of a table. Change the color of part P2 to yellow, increase the weight by 5 and set the city to unknown (single row update) UPDATE P SET COLOR = yellow WEIGHT = WEIGHT + 5 CITY = NULL WHERE P_NUM = P2 ; Double the status of all suppliers in London (multi row update). UPDATE SUPPLIERS SET STATUS = 2 * STATUS WHERE CITY = London ; Deleting Rows The DELETE statement deletes column values in one or more rows of a table. Delete supplier S5 (single row DELETE) DELETE FROM S WHERE S_NUM = S5 ; Delete all shipments with quantity greater than 300 (multirow delete) DELETE S WHERE QTY > 300; Delete all shipments ( SHIPMENTS is then empty!) DELETE S; 5

SELECT Statement The basic SELECT statement retrieves and displays as many rows of data as satisfy the selection criteria you specify. Select all suppliers who are located in Paris. SELECT * FROM SUPPLIERS WHERE CITY = Paris ; The asterix(*) here means that all columns are selected. A WHERE clause consists of one or more search conditions connected by the logical operators AND, OR and NOT. Get all supplier citys SELECT DISTINCT CITY FROM SUPPLIERS; Without the keyword DISTINCT, the result would contain five rows. DISTINCT removes all duplicate rows and hence the result will contain only two rows. Get color and city for "nonparis" parts with weight between 13 and 18 SELECT COLOR, CITY FROM PARTS WHERE CITY <> 'PARIS' AND WEIGHT BETWEEN 13 AND 18; Select all suppliers who are located in a city that has an o as its second letter SELECT * FROM SUPPLIERS WHERE CITY LIKE "?o*"; When using LIKE, the question mark character (?) matches any single character and the asterisk (*) matches any sequence of characters. Select all parts where the color is unknown SELECT * FROM PARTS WHERE COLOR IS NULL; 6

Likewise, parts where the color is known can be selected with the condition WHERE COLOR IS NOT NULL. Select all parts from London, Paris and Rome SELECT * FROM PARTS WHERE CITY IN ("London", "Paris", "Rome"); Instead of OR, the IN syntax together with a group of values can be used. Selecting Data from Multiple Tables (Joins) Selecting data from multiple tables using a single SELECT statement is referred to as a join operation. Do a natural join of suppliers and parts over city SELECT SNUM, SNAME, STATUS, SUPPLIER.CITY, PNUM, PNAME, COLOR, WEIGHT FROM SUPPLIERS, PARTS WHERE SUPPLIERS.CITY = PARTS.CITY; Note: If the condition is left out, the result will be the cartesian product. This query can also be written using the INNER JOIN operation: SELECT SNUM, SNAME, STATUS, SUPPLIER.CITY, PNUM, PNAME, COLOR, WEIGHT FROM SUPPLIERS INNER JOIN PARTS ON SUPPLIERS.CITY = PARTS.CITY; Select all pairs of suppliers such that the two suppliers concerned are colocated. SELECT SUPPLIERS.SNUM, SECOND.SNUM FROM SUPPLIERS, SUPPLIERS AS SECOND WHERE SUPPLIERS.CITY = SECOND.CITY AND SUPPLIERS.SNUM < SECOND.SNUM. By using an alias (in this case SECOND) rows within the same table can be compared. A copy of the table SUPPLIERS called SECOND is created for this purpose. 7

Aggregate functions Function AVG( expression) COUNT(*) COUNT( expression) MAX( expression) MIN(expression) SUM( expression) STDEV(expression) VAR(expression) Meaning Calculates an average value for all field values in the result list Counts the number of rows in the result list (this count includes rows with NULL values). Counts the number of rows in the result list (this count does not include rows with NULL values). Returns the maximum value of expression for all rows. Returns the minimum value of expression for all rows. Calculates the sum of expression for all rows. Returns the standard deviation for the values in expression Returns the variance for the values in expression Get the total number of suppliers SELECT COUNT(*) FROM SUPPLIERS; Get the total number of suppliers in London SELECT COUNT (CITY) FROM SUPPLIERS WHERE CITY = London ; Get the maximum, minimum and average weight from parts. SELECT MAX(WEIGHT), MIN(WEIGHT), AVG(WEIGHT) FROM PARTS; Get the total quantity of part P2 supplied SELECT SUM(QTY) WHERE PNUM = 'P2'; 8

Grouping Data A group is a set of rows that has the same value for a specified column or columns. The GROUP BY clause results in a single row in the result table for each group of rows. Get the part number and the total quantity shipped for each part SELECT PNUM, SUM(QTY) GROUP BY PNUM Get part numbers for all parts supplied by more than one supplier SELECT PNUM GROUP BY PNUM HAVING COUNT (SNUM) >1. The HAVING clause is to groups what the WHERE clause is to rows; in other words, HAVING is used to eliminate groups, just as WHERE is used to eliminate rows. Sorting Data The ORDER BY clause sorts query results by the values in one or more columns. You can specify the columns by name or by order. If you want to sort the results in descending order, you can use the keyword DESC. Ascending is the default sort order. Get all suppliers in ascending order SELECT * FROM SUPPLIERS ORDER BY SNAME. 9

Get the part number and the total quantity shipped for each part. The results should be sorted so the part with the largest total quantity comes first. SELECT PNUM, SUM(QTY) GROUP BY PNUM ORDER BY 2 DESC. Using Subqueries The Query "Get supplier names for suppliers who supply red parts" is usually written: SELECT SNAME FROM SUPPLIERS INNER JOIN (SHIPMENT INNER JOIN PARTS ON SHIPMENT.PNUM = PARTS.PNUM) ON SUPPLIERS.SNUM = SHIPMENT.SNUM AND PARTS.COLOR = Red. 10

But can also be written using subqueries: SELECT SNAME FROM SUPPLIERS WHERE SNUM IN ( SELECT SNUM WHERE PNUM IN ( SELECT PNUM FROM PARTS WHERE COLOR = Red )). The result of a subquery is used as a value in the WHERE clause. You must enclose a subquery in parentheses (), and it can have only one column in its SELECT list. Another type of subqueries use the EXISTS clause: Get supplier names for suppliers who supply part P2 SELECT SNAME FROM SUPPLIERS WHERE EXISTS ( SELECT * WHERE SNUM = SUPPLIERS.SNUM AND PNUM = P2 ). Each SNAME is tested to see if its SNUM causes the EXISTS test to evaluate to true. It is also possible to use subqueries involving NOT IN and NOT EXISTS. 11

The UNION Statement You can use the UNION statement to combine the results of two or more SELECT statements. Get part numbers for parts that either weigh more than 16 OR are supplied by supplier S2 (or both) SELECT PNUM FROM PARTS WHERE WEIGHT > 16 UNION SELECT PNUM WHERE SNUM = S2. Parameters Parameters can be used in questions to change a condition automatically. Ex: PARAMETERS [Choose a supplier number ] text, [Choose a part] text; SELECT S.SNUM, S.SNAME, P.PNUM, P.PNAME, QTY FROM S INNER JOIN (SP INNER JOIN P ON SP.PNUM = P.PNUM) ON S.SNUM = SP.SNUM WHERE S.SNUM = [Choose a supplier number] AND P.PNAME = [Choose a part] ; Each parameter has a name and a data type. When the question is executed, a dialog box is shown for each parameter where you are asked to type in a value. 12