You are on page 1of 42

Self-Paced SQL Exercise

Version 3.5

Basic SQL Exercises

Ingres Corporation

Contents
1 Introduction 4

1.1 Reference Material ................................................................. 4 1.2 Install Ingres ......................................................................... 4 2 Setup 5

2.1 Extract setup Materials ........................................................... 5 2.2 Creating a Database and loading data....................................... 7 2.2.1 2.2.2 Creating database and Connecting ................................... 7 Building Tables .............................................................. 8

2.2.2.1 Getting Help........................................................ 8 2.2.2.2 Creating Tables ................................................... 9 2.2.3 Loading Tables with Data.............................................. 10 2.2.4 2.2.5 3 4 Verify the Data Load .................................................... 10 Troubleshooting .......................................................... 11 13 14

Database Design Exercises 4.1.1 4.2.1

4.1 Simple Retrievals ................................................................. 14 Using Simple Views...................................................... 16 Adding and changing data ............................................ 17 4.2 Data Manipulation ................................................................ 17 4.3 Transaction Processing ......................................................... 20 4.4 Joining Tables ...................................................................... 22 4.5 Views Based on More Than One Table ..................................... 23 SQL Functions ............................................................................. 24 4.5.1 4.6.1 5 Conversion and date functions ...................................... 25 Changing Data Using Subqueries ................................... 28 29 4.6 Unions and Subqueries ......................................................... 26

Solutions 5.1.1 5.2.1

5.1 Simple Retrievals ................................................................. 29 Using Simple Views...................................................... 30 Adding and changing data ............................................ 31 5.2 Data Manipulation ................................................................ 31 5.3 Transaction Processing ......................................................... 34
Ingres Corporation Page 2

Basic SQL Exercises

Ingres Corporation

5.4 Joining Tables ...................................................................... 36 5.5 Views Based on More than One Table ..................................... 37 5.6 SQL Functions ..................................................................... 38 5.6.1 5.7.1 Conversion and date functions ...................................... 39 Changing Data Using Subqueries ................................... 41 5.7 Unions and Subqueries ......................................................... 40

Ingres Corporation

Page 3

Basic SQL Exercises

Ingres Corporation

1 Introduction
This aim of this document is to recap or introduce the basics of SQL using Ingres SQL.

1.1 Reference Material


The Ingres SQL reference http://docs.ingres.com/ guide (SQLREF) is available online at

Ingres Corporation also provides instructor-led training on Ingres SQL. A course description is published at: http://www.ingres.com/services/course-IngresSQL.php . More information on how to attend this training is available at http://www.ingres.com/services/education.php, or contact Ingres Education at education@ingres.com .

1.2 Install Ingres


This self-paced training assumes that you have already installed Ingres. To install Ingres, please download the Ingres installation media from: http://esd.ingres.com/product/Community_Projects/Ingres_Database

To find out how to get started with Ingres, check the Ingres webinars: http://www.ingres.com/about/ondemand-webcasts.php Under the Ingres DBMS category - How to Get Started with Ingres

Ingres Corporation

Page 4

Basic SQL Exercises

Ingres Corporation

2 Setup
2.1 Extract setup Materials
The self-paced training pack contains this document and a set of setup files. Extract these files into an empty folder/directory and open a command prompt within this area. Example Open the zip file:

Click Extract

Choose a target folder, eg c:\tmp

Click Extract. This will create a new folder called setups.

Ingres Corporation

Page 5

Basic SQL Exercises

Ingres Corporation

Open a Command Prompt in the new folder

Ingres Corporation

Page 6

Basic SQL Exercises

Ingres Corporation

2.2 Creating a Database and loading data


2.2.1 Creating database and Connecting 1. Make sure Ingres is started by typing ingstart eg.

2.

At a command line type createdb trainingdb This will create a new database called trainingdb, eg,

3.

Start up the ISQL terminal monitor by typing isql trainingdb at the command line. You will see the following screen:

This is a connection to the database. From the ISQL monitor, we can type SQL commands and execute them using the Go menu item.

Ingres Corporation

Page 7

Basic SQL Exercises

Ingres Corporation

2.2.2 Building Tables 2.2.2.1 Getting Help 1. Within ISQL, type help; commit; eg.

Use the Go menu item to execute the statements. In the output screen, there should be 0 rows,

This verifies that there are no tables available to use yet in this database. Use the End menu item to return to the input screen. Use the same End key to end the ISQL connection. This will return to the command line, eg.

Ingres Corporation

Page 8

Basic SQL Exercises

Ingres Corporation

2.2.2.2 Creating Tables 1. From the command line run the command sql trainingdb < tables.sql eg This will create the tables used in your training and will list the created tables. Verify that the tables have been created. The output should show:

Ingres Corporation

Page 9

Basic SQL Exercises

Ingres Corporation

2.2.3 Loading Tables with Data 1. At the command line view the contents of the file priceinfodata.sql which contains copy-ready data for the priceinfo table eg 2. 3. View the contents of the file data.sql which contains commands to load the tables with data. At the command line run the command: sql trainingdb < data.sql This will load the tables with data.

2.2.4 Verify the Data Load 1. Verify that the data that is now in the priceinfo table by typing the command sql trainingdb < checkrows.sql The expected show result should

Ingres Corporation

Page 10

Basic SQL Exercises

Ingres Corporation

2.2.5 Troubleshooting Ingres errors are reported in the format E_xxxxxx where xxxxxx is an error number. If you see an error when doing setups, check the online documentation (http://docs.ingres.com ). The following checklist might also provide a good starting point for specific problems with the setups: How to start Ingres? o If the ingres system is not running, type ingstart If successful, you will see the following message.

Or if ingres is already running, you will see the following message:

How to connect to an Ingres database? o To test that ingres is running, try a connection to the master database: sql iidbdb If this is successful, you will see a command line prompt:

To quit out of the command line interface, type \q and press return.

Training database does not exist? o To check that the database trainingdb has been created, try a simple connection: sql trainingdb If the connection is successful, you will see a command line prompt (as above). Quit out of the command line interface type \q and press return.

Ingres Corporation

Page 11

Basic SQL Exercises

Ingres Corporation the training

If the connection is unsuccessful, create database by following from steps 2.2.1 above. Cannot find the setups? o o

Check that the setups have been extracted from the zip into a folder. Check that you have launched a command prompt which is in the setups folder. For example, if you have extracted c:\tmp\setups, change to this folder the setups into

Then retry running the setups from step 2.2.2.2 (above).

Ingres Corporation

Page 12

Basic SQL Exercises

Ingres Corporation

3 Database Design
For reference, you will be using a Purchase Order database comprising of the following tables:

vendor PK vendorno vname street city region zip contact integer varchar varchar varchar char varchar varchar 4 30 20 15 2 10 10 PK poheader orderrno integer 4

orddate FK1 vendorno invoiceno status

ingresdate integer 4 varchar 10 char 1

priceinfo PK, FK2 PK, FK1 partno vendorno catno price integer integer varchar decimal 4 4 6 10,2 PK, FK2 PK, FK1

podetail orderno partno qty unit_pr integer integer integer decimal 4 4 2 10,2

part PK partno description integer varchar 4 30

There is also a pohistory table which contains data archived from the poheader table:
pohistory

PK

orderno orddate vendorno invoiceno pototal

integer ingresdate integer varchar money

4 4 10

Ingres Corporation

Page 13

Basic SQL Exercises

Ingres Corporation

4 Exercises
This section contains all the exercises to be carried out. The exercise solutions are provided in Section 5.

4.1 Simple Retrievals


Either a. Using VisualSQL, launch Ingres VisualSQL against the trainingdb database (Start Programs Ingres Ingres VisualSQL). Select the trainingdb from the dropdown box, eg.

Or b. Start up the ISQL Terminal Monitor from the operating system: isql trainingdb

Ingres Corporation

Page 14

Basic SQL Exercises

Ingres Corporation (9 rows)

1.

Display all the rows in the part table, sorted by description.

2.

Display the part description for the part number 4. (1 row)

3.

Display the part numbers currently priced at 230.45 (Hint - current prices are stored in the priceinfo table). (4 rows)

4.

Redisplay the numbers eliminating the duplicates. (3 rows)

5.

Display all parts with descriptions beginning with Pine.

(3 rows)

Ingres Corporation

Page 15

Basic SQL Exercises

Ingres Corporation

4.1.1 Using Simple Views 1. Select all columns of the podetail table that have a quantity greater than 500. (3 rows)

2.

Using the last SQL statement, create a view called vw_large_orders, which includes all columns in the podetail table which have a quantity greater than 500.

3.

Using the new view, retrieve all details for part numbers greater than 2. (2 rows)

Ingres Corporation

Page 16

Basic SQL Exercises

Ingres Corporation

4.2 Data Manipulation


4.2.1 Adding and changing data 1. Add a new row to the part table with the following information: Part number 10 Description Desk chair 2.

(1 row)

Check the result by retrieving the part information for part number 10.

3.

Add a new row to the poheader table with the following information: Order Number 3010 Order Date today Vendor 205 Invoice number inv0101 (Leave the status blank)

(Furniture Heaven (1 row)

4.

Check the result by retrieving the order information for order 3010.

Note that the order date value will be different in your output. Note also that the status column has a default value of P (Pending). 5. Vendor 205 (Furniture Heaven) is no longer supplying Part 5 (Elm Tables). Remove this information from the priceinfo table; (Hint: If you are unsure, select the data, check the result of the select, and then alter the SQL statement from a SELECT to a DELETE). (1 row) First check the data. Then delete the data

Ingres Corporation

Page 17

Basic SQL Exercises

Ingres Corporation

6.

Check the result by retrieving all vendors who still supply part 5. (3 rows)

7.

Select the details from the poheader table that have a status of c (completed). Do not include the status in the results (3 rows)

8.

Add these rows of data from the poheader table into the pohistory. Do not worry about the pototal column at this point. (3 rows) Check the result by retrieving the orders from the pohistory table.

9.

10. Delete from the poheader table, those orders that are now duplicated in the pohistory table (i.e. with a status of c). (3 rows) 11. Check the result of the last statement by retrieving all remaining rows in the poheader table. (4 rows)

Ingres Corporation

Page 18

Basic SQL Exercises

Ingres Corporation

12. Change the invoiceno for order number 3010 to inv00824. (1 row) 13. Check the result by retrieving the details for order number 3010.

Ingres Corporation

Page 19

Basic SQL Exercises

Ingres Corporation

4.3 Transaction Processing


1 Change the price entries in the priceinfo table which are supplied by Vendor no 201. Increase these prices by 1000.00. DO NOT COMMIT YOUR CHANGES. (5 rows) Verify your Results but DO NOT COMMIT YOUR CHANGES.

Vendor 201 did not raise their prices by 1000.00. Rollback the above changes. Verify your results (5 rows)

Change the prices of the parts in the priceinfo table which are supplied by Vendor no 201. Increase these prices by 100.00. Verify and commit your changes. (5 Rows)

Delete all rows in the part table but DO NOT COMMIT YOUR CHANGES. (10 rows)

Ingres Corporation

Page 20

Basic SQL Exercises

Ingres Corporation

Verify that all rows are missing from the part table but DO NOT COMMIT YOUR CHANGES. (0 rows)

Rollback the statement you just entered. Verify that all rows in the part table still exist. (10 rows)

Ingres Corporation

Page 21

Basic SQL Exercises

Ingres Corporation

4.4 Joining Tables


1. Retrieve Order, Part and Quantity information from the view vw_large_orders. (3 rows)

2.

Modify the last command to also display Part descriptions. Do not display the quantity information (3 rows)

3.

Amend the last command so that we see all part numbers, and any large orders for those parts. (? rows)

Ingres Corporation

Page 22

Basic SQL Exercises

Ingres Corporation

4.5 Views Based on More Than One Table


1. Create a view called vw_part_prices to display the all part numbers, descriptions, prices, catalogue numbers and vendor numbers and names for priceinfo entries.

2.

Verify your result by retrieving all the data; sort the result on description. (22 rows)

3.

Use the view vw_part_prices to display all the information, sorted by part number, for parts priced 300.00 or less. (4 rows)

Ingres Corporation

Page 23

Basic SQL Exercises

Ingres Corporation

SQL Functions
1. How many vendors are located in the city of Sheffield? (1 row)

2.

Find the unit price and quantity information for order number 3001. All the information is in the podetail table. (3 rows)

3.

Amend the last query to also include the line item totals for each part. Rename the new column line_total. (3 rows)

4.

Find the total price for order number 3001. Rename the result column total price (1 row)

5.

Use the view vw_part_prices to display the lowest price for each part with a description beginning with Pine (Note: there are some parts which do not have price information. These will be shown with a null price). (3 rows)

Ingres Corporation

Page 24

Basic SQL Exercises

Ingres Corporation

4.5.1 Conversion and date functions 1. Select the 4 rightmost letters of each part description.

(? rows)

2.

Select the 4 rightmost letters of each part description again but converted to upper case (Hint: string functions can be nested). (? rows)

Ingres Corporation

Page 25

Basic SQL Exercises

Ingres Corporation

4.6 Unions and Subqueries


1. Display the order numbers, dates and status for all orders, completed and pending. Remember that all orders in the pohistory table are completed. (Hint: Use a union). (6 rows)

2.

Using the priceinfo table, retrieve prices, Part Numbers and Vendor Numbers, sorted on price. (18 rows)

Ingres Corporation

Page 26

Basic SQL Exercises

Ingres Corporation (2 rows)

3.

Which parts are priced at the lowest price?

4.

Which parts are priced at lower than the average price?

(12 rows)

5.

Amend the last command to also include the part descriptions. (12 rows) Amend the last command to also include the vendor name, street and city information. (12 rows)

6.

Ingres Corporation

Page 27

Basic SQL Exercises

Ingres Corporation

4.6.1 Changing Data Using Subqueries 1. All vendors located in Leeds are increasing their prices by 200.00. Apply this increase to the database. (12 rows) Check the result by retrieving all of the updated prices.

2.

(12 rows)

End of exercise

Ingres Corporation

Page 28

Basic SQL Exercises

Ingres Corporation

5 Solutions
SQL often provides more than one method of correctly solving a request. For this reason, there might be alternative solutions to the solutions which are provided within this section.

5.1 Simple Retrievals


1. Display all the rows in the part table, sorted by description. select * from part order by description; commit; 2. Display the part description for the part number 4. select description from part where partno = 4; commit; 3. Display the part numbers currently priced at 230.45 (Hint - current prices are stored in the priceinfo table). select partno from priceinfo where price = 230.45; commit; 4. Redisplay the numbers eliminating the duplicates select distinct partno from priceinfo where price = 230.45; commit;

Ingres Corporation

Page 29

Basic SQL Exercises

Ingres Corporation

5.

Display all parts with descriptions beginning with Pine. select * from part where description like Pine%; commit;

5.1.1 Using Simple Views 1. Select all columns of the podetail table which a quantity greater than 500. select * from podetail where qty > 500; commit; 2. Using the last SQL statement, create a view called vw_large_orders, which includes all columns in the podetail table which have a quantity greater than 500. create view vw_large_orders as select * from podetail where qty > 500; commit; 3. Using the new view, retrieve all details for part numbers greater than 2. select * from vw_large_orders where partno > 2; commit;

Ingres Corporation

Page 30

Basic SQL Exercises

Ingres Corporation

5.2 Data Manipulation


5.2.1 Adding and changing data 1. Add a new row to the part table with the following information: Part number 10 Description Desk chair insert into part (partno, description) values (10, 'Desk Chair'); 2. Check the result by retrieving the part information for part number 10. select * from part where partno = 10 commit; 3. Add a new row to the poheader table with the following information: Order Number 3010 Vendor 205 (Furniture Heaven Order Date today Invoice number inv0101 (Leave the status blank) insert into poheader (orderno , orddate , vendorno , invoiceno) values (3010 , today , 205 , inv0101); commit; 4. Check the result by retrieving the order information for order 3010. select * from poheader where orderno = 3010; commit;

Ingres Corporation

Page 31

Basic SQL Exercises

Ingres Corporation

5.

Vendor 205 (Furniture Heaven) is no longer supplying Part 5 (Elm Tables). Remove this information from the priceinfo table; (Hint: If you are unsure, select the data, check the result of the select, and then alter the SQL statement from a SELECT to a DELETE). First check the data select * from priceinfo where vendorno = 205 and partno = 5; Then delete the data delete from priceinfo where vendorno = 205 and partno = 5; commit;

6.

Check the result by retrieving all vendors who still supply part 5. select * from priceinfo where partno = 5; commit;

7.

Select the details from the poheader table that have a status of c (completed). Do not include the status in the results. select orderno , orddate , vendorno , invoiceno from poheader where status = 'c'; commit;

Ingres Corporation

Page 32

Basic SQL Exercises

Ingres Corporation

8.

Add these rows of data from the poheader table into the pohistory. Do not worry about the pototal column at this point. insert into pohistory (orderno, orddate , vendorno, invoiceno ) select orderno , orddate , vendorno , invoiceno from poheader where status = 'c'; commit;

9.

Check the result by retrieving the orders from the pohistory table. select * from pohistory; commit;

10. Delete from the poheader table, those orders that are now duplicated in the pohistory table (i.e. with a status of c) delete from poheader where status = 'c'; commit; 11. Check the result of the last statement by retrieving all remaining rows in the poheader table. select * from poheader; commit; 12. Change the invoiceno for order number 3010 to inv00824. update poheader set invoiceno = inv00824 where orderno = 3010; commit; 13. Check the result by retrieving the details for order number 3010. select * from poheader where orderno = 3010; commit;

Ingres Corporation

Page 33

Basic SQL Exercises

Ingres Corporation

5.3 Transaction Processing


1. Change the price entries in the priceinfo table which are supplied by Vendor no 201. Increase these prices by 1000.00. DO NOT COMMIT YOUR CHANGES. update priceinfo set price = price + 1000 where vendorno = 201; 2. Verify your results but DO NOT COMMIT YOUR CHANGES. select * from priceinfo where vendorno = 201; 3. Vendor 201 did not raise their prices by 1000.00. Rollback the above changes. Verify your results. rollback; select * from priceinfo where vendorno = 201; 4. Change the prices of the parts in the priceinfo table, which are supplied by Vendor no 201. Increase these prices by 100.00. Verify and commit your changes. update priceinfo set price = price + 100 where vendorno = 201; select * from priceinfo where vendorno = 201; commit; 5. Delete all rows in the part table but DO NOT COMMIT YOUR CHANGES. delete from part; 6. Verify that all rows are missing from the part table but DO NOT COMMIT YOUR CHANGES. select * from part;
Ingres Corporation Page 34

Basic SQL Exercises

Ingres Corporation

7.

Rollback the statement you just entered. Verify that all rows in the part table still exist. rollback; select * from part; commit;

Ingres Corporation

Page 35

Basic SQL Exercises

Ingres Corporation

5.4 Joining Tables


1. Retrieve Order, Part and Quantity information from the view vw_large_orders. select orderno , partno , qty from vw_large_orders; commit; 2. Modify the last command to also display part descriptions. Do not display the quantity information. select v.orderno , p.partno , p.description from vw_large_orders v join part p on v.partno = p.partno; commit; 3. Amend the last command so that we see all part numbers, and any large orders for those parts. select v.orderno , p.partno , p.description from vw_large_orders v right join part p on v.partno = p.partno; commit;

Ingres Corporation

Page 36

Basic SQL Exercises

Ingres Corporation

5.5 Views Based on More than One Table


1. Create a view called vw_part_prices to display the all part numbers, descriptions, prices, catalogue numbers and vendor numbers and names for priceinfo entries. create view vw_part_prices as select p.partno ,p.description ,pi.price ,pi.catno ,v.vendorno ,v.vname from priceinfo pi join vendor v on pi.vendorno = v.vendorno right join part p on p.partno = pi.partno; commit; 2. Verify your result by retrieving all the data; sort the result on description. select * from vw_part_prices order by description; commit; 3. Use the vw_part_prices to display all the information, sorted by part number, for parts prices 300.00 or less. select * from vw_part_prices where price <= 300 order by partno; commit;

Ingres Corporation

Page 37

Basic SQL Exercises

Ingres Corporation

5.6 SQL Functions


1. How many vendors are located in the city of Sheffield? select count(*) from vendor where city = Sheffield; commit; 2. Find the unit price and quantity information for order number 3001. All the information in the podetail table. select unit_pr , qty from podetail where orderno = 3001; commit; 3. Amend the last query to also include the line item for each part. Rename the new column line-total. select unit_pr , qty , (qty * unit_pr) as line_total from podetail where orderno = 3001; commit; 4. Find the total price for order number 3001. Rename the result column total price. select sum(unit_pr * qty) as total price from podetail where orderno = 3001; commit;

Ingres Corporation

Page 38

Basic SQL Exercises

Ingres Corporation

5.

Use the view vw_part_prices to display the lowest price for each part with a description beginning with Pine (Note: there are some parts that do not have price information. These will be shown with a null price). select description, min(price) from vw_part_prices where description like Pine% group by description; commit;

5.6.1 Conversion and date functions 1. Select the 4 rightmost letters of each part description. select right(description,4) from part; commit; 2. Select the 4 rightmost of each part description again, but converted to upper case (Hint: string functions can be nested). select uppercase(right(description,4)) from part; commit;

Ingres Corporation

Page 39

Basic SQL Exercises

Ingres Corporation

5.7 Unions and Subqueries


1. Display the order numbers, dates and status for all orders, completed and pending. Remember that all orders in the pohistory table are completed. (Hint: Use a union). select orderno, orddate, status from poheader union select orderno, orddate, c from pohistory; commit; 2. Using the priceinfo table, retrieve prices, Part Numbers and Vendor Numbers, sorted on price. select price , partno ,vendorno from priceinfo order by price 3. Which parts are prices at the lowest price? select price , partno ,vendorno from priceinfo where price = ( select min(price) from priceinfo); commit; 4. Which parts are priced at lower than the average price? select price , partno ,vendorno from priceinfo where price < ( select avg(price) from priceinfo); commit;

Ingres Corporation

Page 40

Basic SQL Exercises

Ingres Corporation

5.

Amend the last command to also include the part descriptions. select pa.description , pi.price , pa.partno ,pi.vendorno from priceinfo pi join part pa on pi.partno = pa.partno where pi.price < ( select avg(price) from priceinfo);

6.

Amend the last command to also include the vendor name, street and city information. select pa.description , pi.price , pa.partno ,pi.vendorno , ve.vname , ve.street , ve.city from priceinfo pi join part pa on pi.partno = pa.partno join vendor ve on pi.vendorno = ve.vendorno where pi.price < ( select avg(price) from priceinfo);

5.7.1 Changing Data Using Subqueries 1. All vendors located in Leeds are increasing their prices by 200.00. Apply this increase to the database. update priceinfo set price = price + 200 where vendorno in (select vendorno from vendor where city = Leeds ); commit

Ingres Corporation

Page 41

Basic SQL Exercises

Ingres Corporation

2.

Check the result by retrieving all of the updated prices. select vendorno , price from priceinfo where vendorno in (select vendorno from vendor where city = Leeds );

End of Solutions

Ingres Corporation

Page 42

You might also like