* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download sql - structured query language
Survey
Document related concepts
Microsoft Access wikipedia , lookup
Tandem Computers wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Functional Database Model wikipedia , lookup
Relational algebra wikipedia , lookup
Ingres (database) wikipedia , lookup
Oracle Database wikipedia , lookup
Clusterpoint wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Database model wikipedia , lookup
Transcript
Sheffield Hallam University SCHOOL OF COMPUTING AND MANAGEMENT SCIENCES ___________________________________________________________________ SQL - STRUCTURED QUERY LANGUAGE WORKBOOK NOTE: This workbook is based upon the one written for teaching Oracle SQL to undergraduate students of CMS. Special thanks to the original authors for allowing me to use their work as the basis for this document. The target audience for this version is students on postgraduate courses at CMS, but who have not had SQL experience, or are very rusty. It is a cut down version of the original and is intended only to give some early exposure to the language at the heart of the database elements of the course. The other significant difference is that all examples and questions have been written such that they will run in a variety of environments. Wherever possible standard ISO SQL is used. Where there can be differences, examples are given in both Oracle and MySQL format. Topic Section Introduction and selecting data from tables A Joining tables B Simple functions and grouping data C Subqueries (Oracle users only) D Creating and populating tables and views E Managing the database, access and security F Section A INTRODUCTION The philosophy of Relational Database Systems is that they are easy to understand and use. The standard end-user language for controlling and accessing the database is also simple to learn and use. However, on its own it has limited functionality and sophistication, and leaves much to be desired in terms of enforcing data integrity and can encourage very inefficient use of system resources. Traditionally, a database language comprises 3 different components: DDL - Data Definition/Description Language – used to define and alter the database structure and format DML - Data Manipulation Language – used to manipulate the data values in the database DCL - Data Control Language – used to control user access and processing of the database In Relational Systems, all three components are part of the same language – SQL (Structured Query Language). SQL provides for database definition, population, selection, alteration, structural change and security. Example statements are: DDL - CREATE, DROP, ALTER DML - SELECT, INSERT, UPDATE, DELETE DCL - GRANT, REVOKE (In addition, there are a set of SQL 'commands' - e.g. to set the run-time environment, interrogate the data dictionary etc...). 28/04/17 2 SQL primer workbook 1999/2000 Section A The DATA DICTIONARY Relational databases will have a data dictionary that holds details of the database definition and its environment. This dictionary is implemented using differently with different RDBMS. Some useful commands are:- e.g. DESCRIBE table_name DESCRIBE EMP used to display a table definition The command can be abbreviated to DESC Oracle sees this is an SQL ‘command’ and hence does not need a ; terminator. MySQL, however, does require a closing ; In Oracle you can view the tables you currently own by: SELECT * FROM TAB; In MySQL its: SHOW TABLES; RUNNING SQL(Oracle) The easiest way to run SQL commands, all bar the simplest, is to create text files of SQL command(s) with an editor. If these text files are given an extension of sql (in lower case) e.g. myfile.sql, you can execute the file by typing @ filename or RUN filename at the sql prompt. You can then use the text editor to correct or modify the statements if necessary, re-save the file and execute as required. RUNNING SQL(MySQL) Similarly, one can type commands directly in a the mysql> prompt, or save them for batch mode running in a text file. You run these text files from the command shell using the greater than sign: C:\mysql\bin> mysql <somecode.sql This will carry out the SQL command contained in the file somecode.sql if it is also located in the bin folder. 28/04/17 3 SQL primer workbook 1999/2000 Section A COMMENTING SQL CODE Comments can be included to clarify and explain an sqlplus statement or procedure. The comment starts with /* and ends with */ e.g. SELECT NAME FROM CUST ORDER BY NAME /* this is a piece of simple sql */ /* this sorts the output */ ; These comments work for both Oracle and MySQL. Throughout this workbook the exercises are based on a personnel system and the contents of the tables used are given on the following page. The examples in the text are based on the three tables below, a simple accounts system. The tables represent the fact that a customer may have many accounts, and that an account may be held jointly by more than one customer. CUST Owns CUSTACC Allocated ACC CUST REFNO NAME ADDRESS AREA A123 J Doe 1 High Street Sheffield A124 J Smith 2 West Street Sheffield B127 R Best 4 East Row Rotherham B128 J Best 4 East Row Rotherham C371 R Done 23 Middle Avenue Barnsley CUSTACC REFNO ACCNO A123 1245890 A123 1494315 B127 5418490 B128 5418490 ACC ACCNO BALANCE BRANCH 1245890 234.50 1494315 0.50 5418490 1789.40 28/04/17 Broomhill Tinsley Broomhill 4 SQL primer workbook 1999/2000 Section A THE SAMPLE TABLES EMP EMPNO ENAME JOB MGR HIREDATE SAL 7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER ANALYST PRESIDENT SALESMAN CLERK CLERK ANALYST CLERK 7902 7698 7698 7839 7698 7839 7839 7566 17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 09-DEC-82 17-NOV-81 08-SEP-81 12-JAN-83 03-DEC-81 03-DEC-81 23-JAN-82 800.00 1600.00 1250.00 2975.00 1200.00 2850.00 2450.00 3000.00 5000.00 1500.00 1100.00 950.00 3000.00 1300.00 7698 7788 7698 7566 7782 COMM 300.00 500.00 1250.00 0.00 DEPTNO 20 30 30 20 30 30 10 20 30 20 30 20 10 DEPT DEPTNO 10 20 30 40 DNAME ACCOUNTING RESEARCH SALES OPERATIONS LOC NEW YORK DALLAS CHICAGO BOSTON SALGRADE 28/04/17 GRADE LOSAL HISAL 1 2 3 4 5 700.00 1201.00 1401.00 2001.00 3001.00 1200.00 1400.00 2000.00 3000.00 9999.00 5 SQL primer workbook 1999/2000 13.3.1 Section A The SELECT statement Has the form : SELECT Specification of desired columns FROM Specification of table or tables WHERE Selection criteria for rows GROUP BY Formation of groups with identical values in specified column HAVING Selection of specific groups ORDER BY Sorting sequence of rows of result table The first two arguments SELECT and FROM are mandatory. Selecting data from a single table:SELECT * FROM table-name; e.g. displays all columns SELECT * FROM CUST; It is also possible to manipulate the column values before displaying them:SELECT FROM e.g. column, column2*2.5, column3+column4 alias1, etc.. table-name; displays specified columns, performs arithmetic on columns and specifies an alias to use as a column heading on output SELECT ACCNO, BALANCE*0.1 BONUS FROM ACC; will produce the following:ACCNO BONUS 1245890 1494315 5418490 28/04/17 23.45 0.05 178.94 6 SQL primer workbook 1999/2000 13.3.1 Section A EXERCISES A1 Display the contents of the DEPT, EMP and SALGRADE tables. [Check your results against the tables listed.] Select * from Emp; Select Select To produce an answer to the request "Give a list of all employees showing their employee number, name & department number." will require the following SQL statement, Select EmpNo, Ename, DeptNo from Emp; which will produce the results table shown below. EMPNO 7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 ENAME SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER DEPTNO 20 30 30 20 30 30 10 20 30 20 30 20 10 For all the following exercises record the statement that will give you the required output. Check against the given tables to ensure that the correct rows are selected and save the statements for future reference. (For each section the output from some of the queries is reproduced for you, but after that you are on your own!) A2 28/04/17 Display the name and commission of all the employees. 7 SQL primer workbook 1999/2000 13.3.1 Section A Select ENAME SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER A3 COMM 300.00 500.00 1250.00 0.00 Display the name and commission of all the employees together with another column that shows their commission increased by 10%. Select ENAME SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER A4 28/04/17 COMM NEW_COMM 300.00 500.00 330.00 550.00 1250.00 1375.00 0.00 0.00 Display the job title of all the employees. 8 SQL primer workbook 1999/2000 13.3.1 Section A Select JOB CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER ANALYST PRESIDENT SALESMAN CLERK CLERK ANALYST CLERK To remove duplicates within the result table, use: SELECT DISTINCT column1, column2, etc A5 FROM table-name; Display all the different job titles which currently exist in the company. Select JOB ANALYST CLERK MANAGER PRESIDENT SALESMAN 28/04/17 9 SQL primer workbook 1999/2000 13.3.1 Section A SELECT from a single table using the WHERE condition WHERE =, <>, >, >=, <, <=, (!= means not equal) comparison operators NOT, AND, OR logical operators WHERE column BETWEEN field value AND field value WHERE column IN (field value, field value, ..., ...) WHERE column LIKE '%charstring%' (% means skip n characters; use _ for a single character) WHERE column IS NULL (All these operators can be negated by using NOT) A6 Display the employee number, name and current job of all those who work in Department 30. Select From Where A7 EMPNO ENAME JOB 7499 7521 7654 7698 7844 7900 ALLEN WARD MARTIN BLAKE TURNER JAMES SALESMAN SALESMAN SALESMAN MANAGER SALESMAN CLERK Display the names of all the clerks, showing their employee number and that of their manager. (String matching is case sensitive.) Select A8 Display details of all clerks, analysts and salesmen. Select 28/04/17 10 SQL primer workbook 1999/2000 13.3.1 A9 Section A Display details of employees who are not clerks, analysts or salesmen. Select A10 Display details of all employees whose commission is greater than salary. Select A11 Display employee name, job and department number for employees whose names begin with ‘M’. Select A12 Display details of employees whose salaries are not between £1,200 and £1,400. Select A13 Display details of salesmen and managers in dept 30, whose salary is greater than or equal to £1,500. (Note: with logical operators - AND precedes OR) Select 28/04/17 11 SQL primer workbook 1999/2000 Using the ORDER BY statement to control the display order of selected records ORDER BY column1, column2, etc ASC/DESC; ORDER BY n; (being the nth column) or Note: The default ordering is ascending. Null values are always displayed first regardless of sort sequence. A14 Display the employee number, current job and salary of all those who work in Department 30, with the output in ascending salary order. Select From Where Order By EMPNO 7900 7521 7654 7844 7499 7698 A15 JOB SAL CLERK SALESMAN SALESMAN SALESMAN SALESMAN MANAGER 950.00 1250.00 1250.00 1500.00 1600.00 2850.00 Display the employee name and current job of all those who work in Department 30, with the output in descending salary order. Select A16 Display the employee name and current job of all those who work in Department 30, with the output in descending salary order within each job. Select 28/04/17 12 SQL primer workbook 1999/2000 A17 Display employee details for departments 10 and 30, in name order, within each department Select 28/04/17 13 SQL primer workbook 1999/2000 13.3.3 Section C JOINING TABLES To SELECT data that is held in more than one table the tables need to be “joined” together. The important thing here is the WHERE clause which specifies how the tables are to be joined. SELECT FROM WHERE AND... select-list table_name1, table_name2, , , join-condition Example 1: SELECT FROM WHERE ACCNO, NAME CUST, CUSTACC CUST.REFNO = CUSTACC.REFNO; This will list every account number and the name of the holder(s) ACCNO 1245890 1494315 5418490 5418490 Example 2: SELECT FROM WHERE AND NAME J Doe J Doe R Best J Best C.REFNO, NAME, A.ACCNO, BALANCE ACC A, CUSTACC B, CUST C A.ACCNO = B.ACCNO B.REFNO = C.REFNO; This is similar to the first example but also displays the account balance:REFNO A123 A123 B127 B128 NAME J Doe J Doe R Best J Best C.ACCNO BALANCE 1245890 234.50 1494315 0.50 5418490 1789.40 5418490 1789.40 Note, in the second example A, B and C are temporary labels, called aliases, for the tables and are a useful shorthand in this example. If any column name occurs in more than one table, and that column is used anywhere in the query then it must be identified by specifying the table name as a prefix. If this is not done then an error message indicating that the column name is ambiguous will be returned. 28/04/17 14 SQL primer workbook 1999/2000 13.3.3 Section C Simple Joins (also called an equi-join) are the most common form and return rows from the two tables based upon the equality condition in the WHERE clause (see the examples above) WHERE table1.column_a = table2.column_b (although we could equally well replace the = with a < or >) B1 Predict what results will be obtained by joining the EMP and DEPT tables without specifying any selection criteria, then try it out. How many rows does the result produce? Select B2 Repeat B1 but this time joining EMP to itself. Look carefully at the output to make sure you understand it. (Ensure that you do have results table and not an error message!! Select B3 Find the name and salary of employees in Dallas. Select From Where And ENAME SMITH JONES SCOTT ADAMS FORD 28/04/17 SAL 800.00 2975.00 3000.00 1100.00 3000.00 15 SQL primer workbook 1999/2000 13.3.3 B4 Section C Produce a list that will show the salary grade each employee is on. Display the name, job, salary and grade with the output in ascending order of salary, with those on the same salary ordered alphabetically. Select From Where Order By B5 Display employee name, job, salary and department name for those on grade 3. Select B6 Display details of employees in ACCOUNTING. (Don’t answer this by finding who is in department number 10.) Select B7 Show the name, employee number and manager's name of those who are managed by either Blake or Jones. Do not skip this question. Select 28/04/17 16 SQL primer workbook 1999/2000 13.3.3 B8 Section C Display the employee name, location and department name of those whose salary is greater than £1500. Select How many rows have you selected? Outer Joins Sometimes you want to return all elements of one side of a join, even if there is no entry in the other side. For this we need an outer join. An outer join uses a (+) on the side of the operator where we want to have nulls returned when there is no value match. Consider the Dept table. If you wanted to list all the departments, and list the name of employees who worked in them you could do: SELECT D.DName, E.Ename FROM EMP E, DEPT D WHERE D.DeptNo = E.DeptNo ; But this isn’t a complete list of departments. To get that, using an outer join, one would use the (+) notation thus: SELECT D.DName, E.Ename FROM EMP E, DEPT D WHERE D.DeptNo = E.DeptNo (+) ; Try both and see for yourself. When you come to answering the questions in section C you will need to remember this. 28/04/17 17 SQL primer workbook 1999/2000 13.3.3 Section C SIMPLE FUNCTIONS. SQL provides some simple aggregating functions that enable us to derive information about the rows in a table. COUNT(*) returns a single value, the number of rows in the table MAX(attribute) returns the largest value for the attribute MIN(attribute) returns the smallest value for the attribute AVG(attribute) works out the average value for this attribute SUM(attribute) works out the total value for this attribute SELECT COUNT(*) FROM CUST; returns a single value, the number of rows in the customer table SELECT MIN(BALANCE) FROM ACC; displays the lowest value held in the balance field from all the rows in the accounts table Any of these can be in an SQL statement that includes constraints e.g. SELECT FROM WHERE COUNT(*) CUST AREA = ‘Sheffield'; tells us how many customers are based in Sheffield. For all the following exercises you should check your results carefully against the table listings in section A. C1 What are the lowest and highest basic salaries within the company? Select Minimum_Sal 800 28/04/17 Maximum_Sal 5000 18 SQL primer workbook 1999/2000 13.3.3 C2 Section C How many people have a salary greater than £2000? Select From Where How many people are there in ACCOUNTING? Don’t work out how many people there are in department 10! C3 Select NULL Values If a column has no value for any particular row, it is referred to as a NULL value. This is not the same as a zero in a numeric column, or a space in a character column. The NVL function can be used to convert a null into a specified value e.g. NVL(COMM, 0) will return the actual value of COMM if it has a value, or a zero if COMM is null. This is often necessary when performing calculations, or formatting for output since null values will be totally ignored by many functions and operations. MySQL has a function called COALESCE which allows you do a similar thing. It actually returns the first non-null value in a list, but used as below enables a null to be treated as a specific number: Select ename COALESCE(comm,0) from emp; A column can be tested using IS NULL or IS NOT NULL e.g. SELECT ...FROM... WHERE column_name IS NOT NULL; 28/04/17 19 SQL primer workbook 1999/2000 13.3.3 C4 Section C What are the highest and lowest incomes (i.e. to include commission) in the Sales Department? Select 28/04/17 20 SQL primer workbook 1999/2000 GROUPING DATA The GROUP BY clause splits the table into specified groups, returning one summary row for each group which is then used in the SELECT clause. The following will list the sum of the account balances for each customer (identified by the reference number.) SELECT FROM WHERE GROUP BY REFNO A123 B127 B128 REFNO, SUM(BALANCE) TOTAL CUSTACC C, ACC A C.ACCNO = A.ACCNO REFNO; TOTAL 235.00 1789.40 1789.40 You can only specify fields in the SELECT clause if they are specified in one of the grouping clauses or are part of an aggregating function. What will be the result of the following query? SELECT FROM GROUP AREA, COUNT(*) CUST BY AREA; In each of the following queries, you may treat the President as not an employee (as he isn’t given a deptno). However, here’s a question for the sharper ones: how your queries change if you did need to include him as an employee? C5 How many people are there in each department? Select From Where Group By C6 How many people are there in each type of job in each department? Select 28/04/17 21 SQL primer workbook 1999/2000 C7 For each department, find the average salary and the total salary bill excluding commission. Select C8 Find the maximum commission earned, and the number of people in each department. Select THE HAVING CLAUSE. The HAVING clause is used to specify which GROUPS are to be displayed. WHERE restricts which rows a SELECT works on and HAVING restricts which groups. Example: 28/04/17 SELECT FROM WHERE AND GROUP BY HAVING AREA, SUM(BALANCE) TOTAL CUST, CUSTACC, ACC CUST.REFNO = CUSTACC.REFNO CUSTACC.ACCNO = ACC.ACCNO AREA SUM(BALANCE) > 1000; 22 SQL primer workbook 1999/2000 C9 Display the department name and number of employees in departments with fewer than 6 employees. Select From Where Group By Having C10 Display the names of all the people in a management position, their department name and the number of staff for whom they have direct responsibility. (This is not simply asking for departmental managers.) Select 28/04/17 23 SQL primer workbook 1999/2000 NESTED SUBQUERIES Please note: MySQL (version 3.23.nn) does not yet support nested subqueries. If you are using MySQL you will just need to use your imagination for this section! If we take an example such as to find out which account has the largest balance, thinking about this question logically, it falls into 2 parts. Firstly we need to find out what the largest balance is; secondly we need to find which account this is against. SQL supports this strategy for querying the database through the use of subqueries. The subquery is processed first; the result of the subquery is then substituted into the WHERE clause of the outer query. SELECT FROM WHERE ACCNO, BALANCE ACC BALANCE = (SELECT MAX(BALANCE) FROM ACC); The inner statement will return a single value, in this example £1,789.40. That value is then tested against the value in the balance field of each of the rows in the ACC table. Every row with that value will be returned in the results table:ACCNO 5418490 BALANCE 1,789.40 Care needs to be taken with the WHERE clause. In the example above, the nested SELECT query returns a single value and so the ‘WHERE BALANCE =’ is valid. If the inner SELECT can return several rows then the condition would need to take this into account e.g. WHERE column IN (SELECT…..). You can also use the construct WHERE column > ANY {or > ALL}; In the logic of SQL, WHERE is processed before GROUP BY before HAVING. D1 Who has the highest basic salary? Select From Where = (Select From 28/04/17 ); 24 SQL primer workbook 1999/2000 D2 Which salesman earns the most, including commission? Select From Where And = (Select From Where ); D3 Who in DALLAS has the highest salary? D4 List the names of the people who work with Jones (Employee number 7566) in his department. Select From Where And =(Select From Where 28/04/17 25 ); SQL primer workbook 1999/2000 13.4.4 Section E CREATING AND POPULATING TABLES AND VIEWS (DDL) The CREATE statement Example of a simple table create statement : CREATE TABLE DEPT (DEPTNO DNAME LOC NUMBER(2) , CHAR(12) , CHAR(12)) ; NOTE: MYSQL users: replace Number(2) with SMALLINT This simple version of the CREATE statement does not define integrity constraints (neither entity integrity nor referential integrity). Data Types Data types are undoubtedly the most troublesome aspect of inter-database operations. Even with the simplest of statement, as above, it is quite possible that what works for one database will not work in another. In this case MySQL does not have a NUMBER type. If you find yourself needing to write scripts which work on multiple databases, you will need to find the common types where possible, and then translate to the most appropriate data type for those non-common data types. Oracle would expect you to code the above SQL statement as it is. However, Oracle also recognises most ANSI standard data types and converts them internally. This means that you could equally well have coded the same thing thus: CREATE TABLE DEPT2 (DEPTNO SMALLINT , DNAME CHAR(12) , LOC CHAR(12)) ; This causes no error since Oracle converts SMALLINT to Number(38). You can prove this by asking Oracle to describe the table (DESC DEPT2) and you will see the data type is not defined as SMALLINT, even though that is how you coded it. Knowing that SMALLINT is valid in both MySQL and Oracle environments means you could save the latter code and use it in both databases. This is an example of finding the common data types. Do not get too worried about this, however. Most Oracle professionals will spend most of their time using Oracle only, and will never need to translate between databases. Each column must have a name and a data type assigned to it. The declaration of the data type determines the operations that may be performed on the data. E.g. 28/04/17 26 SQL primer workbook 1999/2000 13.4.4 Section E string variables will be sorted alphabetically, i.e. in ASCII code order, and numeric data will be sorted numerically. The main data types supported by the version of SQL used on the course are shown in the table below:Oracle Data Type MySQL Data Type CHAR(n) CHAR(n) CHARACTER(n) CHARACTER(n) VARCHAR2(n) VARCHAR(n) Variable length character string, having a maximum length of n. n<2001, default 1. Needs less storage if strings are of mixed lengths, but not ANSI standard LONG LONGTEXT Variable length character string, having a maximum length of 2 gigabytes (both databases) NUMBER(p, s) NUMERIC(p,s) Number having size p and s decimal places. NUMBER(n) TINYINT Integer of size n (Oracle), Tinyint = 1 byte SMALLINT SMALLINT Translated to Number in Oracle, 2 bytes in Mysql BIGINT 8 bytes DATE Dates ranging from 1/1/4712BC to 31/12/4712AD. Oracle uses a single data type for both dates and time, so even when you declare as a date, you are actually storing: DATE TIME DATETIME 28/04/17 Description Fixed length character string of n characters. n<256, default n=1. Always padded to n. century, year, month, day, hour, minute, second MySQL does allow you to store DATE only, TIME only, or DATETIME. 27 SQL primer workbook 1999/2000 14.2, 14.3 Section E The CONSTRAINT clause The flexibility and ease of use of Relational Databases is achieved at a cost - data integrity is sacrificed. It is possible to create databases which allow users to delete important cross-referenced data, to create inconsistencies within the data values and to produce invalid output from an SQL procedure. Semantic integrity constraints may be applied to : a single column in a table e.g. Salary must be between 1000 and 30000 Sex code must be 'M' or 'F' multiple columns in a table e.g. Start date must be greater than Birth date multiple rows in a table e.g. Salary of employee must be less than salary of manager Existence constraints apply to 2 or more rows in different tables: A row in an Order table cannot be created unless there is a corresponding row in the Customer table. The constraint clause can be applied to a column (or group of columns) as part of the CREATE and ALTER TABLE statements. The constraint is checked and applied when an INSERT, UPDATE or DELETE statement is run against that table. Constraints may impose the following combinations of rules : . require that the value of a column(s) is NOT NULL . require that the value of a column(s) is UNIQUE within the table . identify a column(s) as the PRIMARY KEY . require the value of a column(s) to exist in another table as a FOREIGN KEY . require the value in a column to conform to an expression (CHECK) Note : PRIMARY KEY is a superset of UNIQUE UNIQUE requires NOT NULL to be specified UNIQUE cannot be applied to PRIMARY KEY 28/04/17 28 SQL primer workbook 1999/2000 14.2, 14.3 Section E Each constraint may be optionally named so that it can be located in the data dictionary. If a constraint is not named then it cannot be identified to be used within a MODIFY statement. The easiest way to implement constraints is as part of the field declarations in the CREATE statement e.g. CREATE TABLE Dept (Deptno NUMBER Dname Loc CHAR(12) CHAR(12) PRIMARY KEY CHECK (Deptno BETWEEN 10 AND 99), CHECK (Dname = UPPER(DNAME)), CHECK (Loc IN ('DALLAS', 'BOSTON', 'NEW YORK'))); The constraints may also be defined as separate clauses at the end of the CREATE statement but still within it e.g. CREATE TABLE Dept2 ( Deptno NUMBER, Dname CHAR(12), Loc CHAR(12), PRIMARY KEY (DEPTNO), CONSTRAINT dept_pk CHECK (Deptno BETWEEN 10 AND 99), CONSTRAINT dname_ck CHECK (Dname = UPPER(DNAME)), CONSTRAINT loc_ck CHECK (Loc IN ('DALLAS', 'BOSTON', 'NEW YORK'))); Oracle automatically enforces NOT NULL on column(s) defined as Primary Keys. MySQL need you to defined the column as NOT NULL first: SAME EXAMPLE in MYSQL: CREATE TABLE Dept2 ( Deptno Integer NOT NULL, Dname CHAR(12), Loc CHAR(12), PRIMARY KEY (DEPTNO), CONSTRAINT dept_pk CHECK (Deptno BETWEEN 10 AND 99), CONSTRAINT dname_ck CHECK (Dname = UPPER(DNAME)), CONSTRAINT loc_ck CHECK (Loc IN ('DALLAS', 'BOSTON', 'NEW YORK'))); 28/04/17 29 SQL primer workbook 1999/2000 14.2, 14.3 Section E This method is the only way to handle compound primary keys:CREATE TABLE Order_Detail (Order_Id NUMBER, Part_Number NUMBER, Quantity NUMBER, PRIMARY KEY (Order_Id, Part_Number)); MySQL Version: CREATE TABLE Order_Detail (Order_Id INTEGER NOT NULL, Part_NUMBER INTEGER NOT NULL, Quantity INTEGER, PRIMARY KEY (Order_Id, Part_NUMBER)); To establish referential integrity the column(s) in the related table must have foreign key references defined on them:CREATE TABLE Order_detail2 (Order_id NUMBER, Part_number NUMBER, Quantity NUMBER, PRIMARY KEY (Order_id, Part_number), FOREIGN KEY (Order_id) REFERENCES Order(Order_id), FOREIGN KEY (Part_number) REFERENCES Part(Part_number)); This table must be created after the tables named Order and Part, both of which must have the referenced columns defined as primary keys. NOTE, MySQL users: The FOREIGN KEY syntax in MySQL exists only for compatibility with other SQL vendors' CREATE TABLE commands; it doesn't do anything. There are real performance issues around foreign keys. You should use them by default, and certainly in the majority of cases they are sensible. However, whilst it is hard to give rules for when not to use them, please remember that they can be a place to look for improvements if performance becomes an issue. If you can guarantee that data that is being entered is consistent with the relationships (and perhaps able to enforce that at the client end) you will save the database doing a lot of work during inserts and updates on tables which contain these constraints. 28/04/17 30 SQL primer workbook 1999/2000 14.2, 14.3 E1 Section E Create the three tables which implement the Customer database that was described in Section A. Ensure that you have implemented the primary keys correctly and set up the referential integrity. (If you need to delete a table the command is DROP TABLE table_name.) CREATE CREATE CREATE The ALTER statement An existing table can be altered at any time by adding table elements, modifying column definitions and dropping constraints. E.g. Or Or Or 28/04/17 ALTER TABLE Order_detail ADD Order_date DATE; Creates a new column ALTER TABLE Order_detail MODIFY Part_number CHAR(5); Changes the data type ALTER TABLE Dept DROP CONSTRAINT dname_ck; Removes the format constraint ALTER TABLE Order_detail MODIFY (Quantity NOT NULL); Requires a value in the column 31 SQL primer workbook 1999/2000 13.3.10 Section E The INSERT statement Values are inserted into a table one row at a time e.g. INSERT INTO CUST (REFNO, NAME, ADDRESS. AREA) VALUES ('A123', ‘J Doe’, ‘1 High Street’, ‘Sheffield’) ; (Note the mandatory single quote marks around character strings, this also applies to the entering of dates). If we are supplying a value for every field in the row then we can omit the references to the field names, provided the values are presented in the same sequence as the fields appear in the table. INSERT INTO ACC VALUES (1245890, 234.5, ’Broomhill’) We can also insert rows into a table with data values missing, provided we don’t try to omit values which are defined as mandatory (not null) e.g. the primary key, but this will require us to specify the columns into which we are entering data. INSERT INTO ACC (ACCNO) VALUES (1255546); will insert a new row with an account number set up and the remaining columns null. E2 Populate the tables that you created in Exercise E1 with the data as given in Section A. Give an example of each insert statement in the boxes below. Insert Insert Insert The DELETE statement 28/04/17 32 SQL primer workbook 1999/2000 13.3.10 Section E The DELETE statement is used to remove rows from a table. WHERE clause to specify which rows are to be deleted:DELETE FROM WHERE This requires a CUST REFNO = ‘A123’; Unlike the INSERT which operates on a row at a time, DELETE will remove all the rows that satisfy the ‘where’ condition - so beware! E3 R Best has decided to transfer her business from the bank. Delete all the information about her from the database. The UPDATE statement To change the data values in the database use the UPDATE statement UPDATE is similar to DELETE in that it can operate on a set of rows that meet a specific condition, not just a single row. UPDATE SET WHERE E4 ACC BALANCE = 500 ACCNO = 1245890; J Best has moved to 31 Hanover Street, Chapeltown. Amend the data in the Customer table to reflect this change. In Summary:Adding rows 28/04/17 INSERT INTO table_name (column1, ....) 33 SQL primer workbook 1999/2000 13.3.10 Section E VALUES (field_value1,....); Updating / Modifying UPDATE SET WHERE table_name column = field_value test condition; Deleting / Removing DELETE FROM WHERE table_name test condition; 28/04/17 34 SQL primer workbook 1999/2000 14.4 Section F The COMMIT statement This may be issued to make permanent on the database all changes caused by the last transaction. A transaction is 'a logical unit of work' and a 'unit of integrity' in that it takes the database from one known state to another. In between these states, the database may be partially updated and inconsistent. A normal QUIT from ORACLE or the execution of a DDL statement will automatically cause a commit. A commit also releases the transaction's locks (this is concurrency control). As an alternative to having to issue a commit, this can be performed automatically after each successful sql statement by setting AUTOCOMMIT ON. The current state of autocommit can be seen by the SHOW AUTOCOMMIT statement. By default, MySQL runs in autocommit mode. This means that as soon as you execute an update, MySQL will store the update on disk. The SAVEPOINT statement (Oracle Only) If autocommit is off a savepoint can be issued at a suitable stage during a transaction (a set of sql statements):e. g. SAVEPOINT stage 2; This is a useful facility if the sql is embedded within an application program that may contain several functions. If an error occurs it is possible to return the database state to that just prior to the function that failed, rather than have to re-run the entire application. The ROLLBACK statement (Oracle Only) This will undo the effects of the last transaction:e.g. ROLLBACK We can also rollback to a specified savepoint:e.g. ROLLBACK TO SAVEPOlNT stage_2; 28/04/17 35 SQL primer workbook 1999/2000 Appendix INDEXES ORACLE uses indexes to improve performance when accessing tables in the index column order searching for rows with specified index column values. However; an index slows down insertions; deletions and changes in indexed column values. Several indexes may be created on the same table using different columns. Null values are not indexed. CREATE INDEX ON name table-name (column,...... ); or CREATE UNIQUE INDEX name ON table-name (column,...... ); Example CREATE INDEX Customers ON CUST (Area, RefNo) This will create an index on the table CUST that will order the records alphabetically by area and then by reference number within each area. i.e:REFNO NAME ADDRESS AREA C371 R Done 23 Middle Avenue Barnsley B127 R Best 4 East Row Rotherham B128 J Best 4 East Row Rotherham A123 J Doe 1 High Street Sheffield A124 J Smith 2 West Street Sheffield Indexes are used to a) speed up retrieval of rows from the table and/or b) enforce uniqueness on values in a column. F3 Create a unique index on the EMP table using the column ename and then try to enter the following record. EMPNO 7599 28/04/17 ENAME JONES JOB CLERK MGR 7839 36 HIREDATE 02-APR-81 SAL COMM 975 DEPTNO 20 SQL primer workbook 1999/2000