SQL was defined in the late 60 s, early 70 s by the System R research group at IBM.

Size: px
Start display at page:

Download "SQL was defined in the late 60 s, early 70 s by the System R research group at IBM."

Transcription

1 Introduction to SQL: SQL was defined in the late 60 s, early 70 s by the System R research group at IBM. Large numbers of products are available based on SQL with minor/major changes in syntax. ORACLE SQL is the only product that can be used in Getting help: Go to There you will find instructions for Logging into ORACLE Downloading DBs used in class under instructions How to reset your password if you ve forgotten it. Logging on: sol:~>sqlplus joan SQL*Plus: Release Production on Thu Jun 14 16:13: Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved. Enter password: Connected to: Oracle Database 11g Enterprise Edition Release bit Production With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP, Data Mining and Real Application Testing options SQL> Now you can enter queries. To exit type exit or quit ( I have stored queries, noted in red you do not have access to them!) 1

2 All SQL statements must end with a semicolon (select, drop, create, alter, grant and revoke). Everything else does not require semicolon Note: / works too as a terminator but ; is the convention. Note: for later use, to display stored queries set echo on & set pause on Entering queries and correcting mistakes: The most recently executed SQL statement is held in a buffer and you can reexecute it with / or run. Run will display the query first. List displays the buffer contents. For example: SQL> select * (q1) 2 from inv 3 where description = 'NUT'; PARTNO DESCRIPTION QONHAND NUT NUT 1100 SQL> / PARTNO DESCRIPTION QONHAND NUT NUT 1100 SQL> run 1 select * 2 from inv 3* where description = 'NUT' PARTNO DESCRIPTION QONHAND NUT NUT 1100 SQL> list 1 select * 2 from inv 3* where description = 'NUT' 2

3 Note that the above commands will NOT work with stored queries unless they are in the buffer. Oracle will give the line number of errors in a query. To correct, make this the current line number and use change to correct error. Format is change/old/new as in below: SQL> select * 2 from invv 3 where description = 'NUT'; from invv * ERROR at line 2: ORA-00942: table or view does not exist (q2) SQL> 2 2* from invv SQL> change/invv/inv 2* from inv SQL> list 1 select * 2 from inv 3* where description = 'NUT' SQL> Note use of single quotation marks around strings also case sensitive. Input allows input of lines after the current line; del deletes the current line e.g. del 3 deletes line 3. Then we can do the following: SQL> 2 (not stored) 2* from inv SQL> input where description = 'NUT'; SQL> list 1 select * 2 from inv 3* where description = 'NUT' SQL> 3

4 Save is used to store the current query for example: SQL> select qonhand 2 from inv 3 where qonhand = 700; (q3) QONHAND SQL> save query1 Created file query1.sql SQL> start query1 QONHAND will also work to re-run the stored query. Convention is store q1, q2, q3 etc... However, the convention is not very useful. Personally I find it better to save queries with a meaningful name such as build-spj-table. 4

5 The Select statement: format is Select From [where] [group by] [having] [order by] 1. Must have select and from, others are optional 2. Order Must be as above 3. Can t have having without a group by 4. Can have group by on its own. 5. set pages {#} will set the number of lines displayed 6. Usually write each clause on a separate line. Convention and makes it easier to correct mistakes! 5

6 Basic Features: Get the supplier table (note that attribute is supno not suppno! Unintentional mistake, but makes some queries simpler!) SQL> select * from supp; (q4) Get only the supplier numbers from supp SQL> select supno from supp; (q5) Get inventory details about bolts SQL> select * from inv where description = 'BOLT'; (q64) Get part numbers from quot SQL> select partno from quot; (q64a) Get distinct part numbers duplicates removed. Duplicate removal expensive! SQL> select distinct partno from quot; (q65) 6

7 Get quotations for parts 207 and 209 CAN T use and here in SQL. Remember that English is not the same as logical equivalences. It is because each row/col position can only have one value. SQL> select * from quot where partno = 207 or partno = 209; (q66) Get quotations for all parts except 207 shows the use of not is strange! Note <> or!= will work as expected. The following appears logical SQL> select * from quot where partno not = 207; (q67) However try.. SQL> select * from quot where not partno = 207; (q68) Also try.. SQL> select * from quot where partno <> 207; (q65a) and SQL> select * from quot where partno!= 207; (q65b) 7

8 Get inventory details for bolts, washers and nuts (lists make queries shorter!) SQL> select * from inv where description in ('BOLT', 'WASHER', 'NUT'); (q6) Use of not... in... SQL> select * from inv where not description in ('BOLT','WASHER','NUT') (q7) SQL> select * from inv where description not in ('BOLT','WASHER','NUT'); (q7a) Get quotations for parts in the price range 8 to 20. Always inclusive. SQL> select * from quot where price between 8 and 20; (q8) The use of not... between... SQL> select * from quot where not price between 8 and 20; (q9) SQL> select * from quot where price not between 8 and 20; (q9a) 8

9 Get quotations where the value of goods on order is > 100 (i.e. price * qonorder > 100). Shows use of expressions in SQL. SQL> select * from quot where price * qonorder > 100; (q10) Can we print the expression? Yes! SQL> select price*qonorder from quot where price*qonorder > 100; (q11) To give a more meaningful answer to the user, try.. SQL> select suppno, partno, price*qonorder (q11a) 2 from quot where price*qonorder > 100; However, some things do not work! Try SQL> select *, price*qonorder 2 from quot 3 where price*qonorder>100; (q11b) 9

10 Built in Functions: AVG, SUM, MAX, MIN, COUNT Get the average price and total quantity on order for part 221 SQL> select avg(price), sum(qonorder) from quot where partno = 221; (q12) Let s try (q12a) to see what happens SQL> select partno, avg(price), sum(qonorder) from quot where partno = 221; How many quotations are there for part 231? SQL> select count(*) from quot where partno= 231; (q13) Use of count: Counting suppliers:- SQL> select count(supno) from supp; (q14b) SQL> select count(distinct suppno) from quot; (q14c) How many quotations do we have? SQL> select count(*) from quot; (q14) 10

11 How many parts do we have quotations for? Note partno is not the PK! SQL> select count(partno) from quot; (q14d) Removing duplicates is expensive (involves ordering) but necessary sometimes.. SQL> select count (distinct partno) from quot; (q14a) What is the maximum and minimum price for part 228? SQL> select max(price), min(price) from quot where partno = 228; (q16) To make the answer more meaningful sort of SQL> select 'The answer =', max(price) from quot; (q16b) Note: 1. An aggregate function may not be part of the where clause. See (q16a) 2. If using an aggregate function (without a group by) then the select clause may only contain literals and columns which have functions applied to them. See (q12a), (q16b) 11

12 Use of Distinct: a bit different from what you might expect! How many suppliers and parts are there? N.B. Don t need brackets for distinct. SQL> select distinct suppno, partno from quot; (q16c) Is this what we expected???? Try (q16d)! What do you expect to happen? SQL> select count(distinct suppno, partno) from quot: (q16d) However SQL> select count(distinct suppno), 2 count(distinct partno) from quot; (q16e) Selecting data from two or more tables: Must tell SQL where the data is coming from..ie which table and have to connect the tables ( in relational terms we do a join of the two tables over partno). Different ways to do this. Get the partno, description and price for parts supplied by suppno 54 SQL> select inv.partno, description, price 2 from inv, quot 3 where inv.partno = quot.partno 4 and suppno = 54; (q17) Note: you must use the table name, or a qualifier, where there is ambiguity - e.g. partno in two tables. Line 3 ensures that you are getting the right info about the same part from both tables. Technically, it is a join of the tables at a lower level. More later! 12

13 For each supplier get the combined cost of part 221 and 231 ( shows use of qualifier). This is a difficult query - but instructive as we need two pointers to the same table as we re combining info within one table. SQL> select a.suppno, a.price + b.price 2 from quot a, quot b 3 where a.suppno = b.suppno 4 and a.partno = 221 and b. partno = 231; (q19) Group by: used with aggregate functions. Will return one row for each value of the column(s) grouped. For each part, what is its average price? For each part use group by Question: why is line 1 OK? It has an column and an aggregate function??? SQL> select partno, avg(price) 2 from quot 3 group by partno; (q20) What about this query? What would you expect? SQL> select suppno, partno, avg(price) 2 from quot 3 group by suppno, partno; (q20a) Exercise: Try For each part, what is the total (i.e. sum) quantity of parts on order (q21) 13

14 We can place restrictions on groups, for example: For each part where there is more than one quote, what is the average price of that part? SQL> select partno, avg(price) 2 from quot 3 group by partno 4 having count(*)>1; (q22) Exercise: How will the answer be different if we delete line 4? (q22a) NOTE: When using a group by, all columns in the select clause must have a function applied to them or have a group by applied to them. 14

15 Subqueries: can be used as an alternative to a join (see q17). Note that the innermost query is evaluated first. Get the inventory details for parts supplied by supplier 54. SQL> select * from inv 2 where partno in 3 (select partno from quot where suppno = 54); (q23) Exercise: Try doing it using a join.. (q23a) Can we select just one (or more) columns? Yes! SQL> select qonhand from inv 2 where partno in 3 (select partno from quot where suppno = 54); (q24 & q24a) 15

16 Get the inventory details for parts supplied by TITANIC PARTS. SQL> select * from inv 2 where partno in 3 (select partno from quot 4 where suppno in 5 (select supno from supp 6 where name = 'TITANIC PARTS')); (q25) Exercise: Try doing the query using joins (q25a) Cases where we must use subqueries: Get the supplier number, part number and price for each part where the price is less than the average price for that part. SQL> select partno, suppno, price 2 from quot where price < avg(price) (q26a) SQL> select partno, suppno 2 from quot where price < (select avg(price) from quot); (q26b) Exercise: comment on these solutions! 16

17 What about the following? SQL> select suppno, partno, price 2 from quot a 3 where price < (select avg(price) 4 from quot 5 where a.partno = partno); (q26) Set operations: union, intersection and minus sometimes very convenient! Simple examples here. List the parts where qonhand is > 50 OR the qonorder is > 50. SQL> select partno from inv where qonhand>50 2 union 3 select partno from quot where qonorder>50; (q27) Note: can t use UNION inside a subquery List the parts where the qonhand is >50 AND the qonorder is >50. SQL> select partno from inv where qonhand>50 2 intersect 3 select partno from quot where qonorder>50; (q28) List parts where qonhand is > 50 MINUS where the qonorder is > 50. SQL> select partno from inv where qonhand > 50 2 minus 3 select partno from quot where qonorder > 50; (q29) 17

18 Testing for existence: very important concept for more advanced queries. Get supplier names who give quote for parts where the delivery time is < 10. SQL> select name from supp 2 where exists ( select * from quot where delivery_time < 10 3 and supno = suppno); (q30) Note that the subquery will return either true or false. If the subquery is true the where exists is true and the name is selected. Otherwise, if the subquery returns false the where exists is false and the name will not be part of the answer. Also, in some we can use a subquery or some other method to get the answer. What parts supplied by supplier 53 are also supplied by supplier 61? (Can be done using subquery (q40b) or intersection (q40c) also.) SQL> select partno from quot p 2 where exists (select * from quot q 3 where p.suppno = 53 and q. suppno = 61 4 and p.partno = q. partno); (q40) To check answer: Parts supplied by 53: 222, 228, 232, 241, 273 and 295 Parts supplied by 61: 209, 221, 222,

19 Not exists works slightly differently but is equally important. In this case, again, the subquery will return either true or false. If the subquery is true the where not exists is false and the partno is not selected. Otherwise, if the subquery returns false the where not exists is true and the partno will be part of the answer. Get part numbers for parts supplied by 53 but not supplied by 61. (Can be done using subquery (q41a) or minus (q41b) also.) SQL> select partno from quot p 2 where suppno = 53 3 and not exists ( select * from quot q 4 where suppno = 61 and p.partno = q.partno); (q41) To check answer: Parts supplied by 53: 222, 228, 232, 241, 273 and 295 Parts supplied by 61: 209, 221, 222, 241 Important: can replace * with 1 or any string in these types of queries e.g. (q30a) & (q30b). Remember that in some cases you do want * as you want to retrieval all rows, see (q4). More efficient as * requires SQL to read all records. With where exists we just need to find one row satisfying the condition. With where not exists also we do not always need to look at all the records. 19

20 Advanced SQL: need to have covered calculus to do some of these queries and some queries are easier to do if we state them in calculus first and translate in SQL. SQL queries that require for all and if then : Not available in SQL so use math equivalences instead: 1. x (f) x ( f) or = 2. x y(f) x y(f) or = 3. If A then B A B 4. Not ( A B) A B 5. x (A B) x (A B) or ( if A then B) = (A and B) Note: We mostly use #2 and #5!! Method: 1. Translate English query in relational calculus 2. Transform into negated version using logical equivalences above 3. Transform into SQL! 20

21 Note: we are using a different database now! Examples: note that in the Oracle DB the attribute names for the SPJ database are the same EXCEPT for sno (S#), pno (P#) and jno (j#). Get the names of suppliers who supply all projects (part not important) sx.sname where jx spjx s.t. spjx.s# = sx.s# & spjx.j# = jx.j# sx.sname where jx spjx s.t. spjx.s# = sx.s# & spjx.j# = jx.j# SQL> select sname from s where not exists 2 (select * from j where not exists 3 (select * from spj where 4 spj.sno = s.sno and spj.jno = j.jno)); (q42) Note that the join conditions always remain the same! 21

22 Get the names of the suppliers who supply all the red parts. (Subset.. if.. then) sx.sname where px (if px.colour = red) then spjx s.t. spjx.s# = sx.s# & spjx.p# = px.p# sx.sname where px s.t. px.colour = red and spjx s.t. spjx.s# = sx.s# & spjx.p# = px.p# SQL> select sname from s where not exists 2 (select * from p 3 where color = 'RED' and not exists 4 (select * from spj 5 where spj.sno = s.sno and spj. pno = p.pno)); (q43) Note: can NOT move red condition or will get wrong answer see (q43a), where we have moved the red condition to another clause. 22

23 Get the names of suppliers who supply all the parts supplied by s1. (Subset.. if.. then) sx.sname where spjx ( if spjx.s# = s1) then spjy s.t. spjy.s# = sx.s# & spjy.p# = spjx. p# sx.sname where spjx s.t. spjx.s# = s1 and spjy s.t. spjy.s# = sx.s# & spjy.p# = spjx. p# SQL> select sname from s where not exists 2 (select * from spj x 3 where sno = 'S1' and not exists 4 (select * from spj y 5 where s.sno = y.sno and x.pno = y.pno)); (q44) Strictly speaking, we only need the tuple variable x but using both x and y can help avoid confusion! Always good in an exam! However, because we are using the spj table twice we do need at least one tuple variable, see (q44a) & (q44b no tuple variable so wrong answer). 23

24 Get the part numbers for parts supplied to all London projects. (Subset.. if.. then) px.p# where jx ( if jx.city = London then spjx s.t. spjx.j# = jx.j# & spjx.p# = px.p# px.p# where jx s.t. jx.city = London and spjx s.t. spjx.j# = jx.j# & spjx.p# = px.p# SQL> select pno from p where not exists 2 (select * from j where city = 'LONDON' and not exists 3 (select * from spj where pno = p.pno and jno = j.jno)); (q45) Note: in line 3 we don t need a qualifier (tuple variable) for the spj table. 24

25 Creating Tables: Must drop tables before trying to create them if they already exist otherwise problems with non-unique constraint names! However if a FK is defined on the table then must drop FK or table first.. complicated! Important for lab exams!! Create the S table for the suppliers relation of the SPJ DB. Note that using not null and primary key constraint gives entity integrity. First look at creating with just a Primary Key constraint: SQL> create table suppliers 2 (sno integer not null, 3 sname varchar2 (15), 4 status integer, 5 city varchar2 (10), 6 Constraint sno_pk Primary Key (sno)); (q48) Now, define a Foreign Key. Note if you are defining a foreign key on a table, that table MUST exist already. So, below, suppliers must be created first with sno defined as a primary key. Remember FKs are defined on PKs. SQL> create table shipments (q49) 2 (sno integer not null unique, 3 pno integer not null unique, 4 jno integer not null unique, 5 qty integer, 6 CONTRAINT sno_fk FOREIGN KEY (sno) REFERENCES suppliers(sno)); All constraint names must be unique so we can reference them. 25

26 Foreign keys for pno and jno can be added after the parts and jobs tables are created: for example Alter table shipments Add constraint pno_fk Foreign Key (pno) references Parts (pno); Putting it all together: Creating the quot table: SQL> create table quotations (q49a) 2 (s# integer not null, 3 p# integer not null, 4 price number, 5 del_time integer, 6 on_order integer, 7 constraint sp#_pk primary key (s#, p#), 8 constraint supp#_fk foreign key (s#) references supp(supno), 9 constraint part#_fk foreign key (p#) references inv(partno)); Other examples: q90 and q200 (where FK references a PK within the same table). Note that we can define the PK constraint in one statement but need one statement for each FK constraint. Both together ensure both entity and referential integrity. 26

27 Can create tables in a simpler way but NOT recommended as constraints can not be removed at a later date. For example: SQL> create table employee (query90a) 2 (name varchar2(20) not null, 3 ID varchar2(10), 4 manager varchar2(20), 5 DOB char(10), 6 Sin char(10), 7 dept varchar2(20), 8 salary decimal(10,2), 9 PRIMARY KEY (ID), 10* FOREIGN KEY (manager) REFERENCES employee(id)); Table created. As there are no constraint names, they can not be removed. So use constraint names for later use you never know when you will need to change a constraint! To drop a constraint: alter table quotations drop constraint partno_fk 27

28 Note that the actual answers to these and the following questions depend on what has been entered and deleted from the relation(s) previously. Adding data to tables: One row at a time... SQL> insert into suppliers values(3, 'Date', 200, 'Windsor'); (q50) & (q51) Or easier for one row at a time. SQL> insert into suppliers values (&sno, &sname, &status, &city); (q52) To enter Frank s as a sname use Franks s Strange! SQL> insert into suppliers values (177, 'Frank''s', 400, 'Vancouver'); use q52 Using nulls: SQL> insert into suppliers values (50, null, null, null); (q53) SQL> select * from suppliers where status is null; (q54) SQL> select * from suppliers where status is not null; (q55) 28

29 Deleting data: to delete a row (s). Need to be careful when deleting!!! SQL> delete from suppliers where city = 'Paris'; (q56) To delete a table (deletes all rows and views defined on the table) SQL> drop table suppliers; (q57) Note: if a FK references the table then it can t be dropped until the table containing the FK is dropped first. For example, can t drop S before SPJ. Updating a row... SQL> update suppliers 2 set status = where sno = 4; (q58) More than one row... SQL> update suppliers 2 set city ='Paris' where city = 'Dublin'; (q59) Increase all status values by note that null = null! 29

30 SQL> update suppliers 2 set status = status + 200; (q60) Creating views: SQL> create view ParisSuppliers as 2 select * from s where city = 'PARIS'; (q61) & then (q61a) Can rename columns in a view... SQL> create view SupplierStatus (Name, Points) as 2 select sname, status from s; (q62) SQL> select * from SupplierStatus; (q63) Note: views are stored as queries not tables. To drop a view: Drop view <name> ; 30

31 An introduction to PL/SQL: PL/SQL is an Oracle Procedural Language (PL) extension of SQL. PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation in the early 90 s to enhance the capabilities of SQL. With PL/SQL, you can use all SQL statements. PL/SQL fully supports SQL data types. With PL/SQL, an entire block of statements can be sent to the database for execution at one time. This can drastically reduce network traffic between the database and an application. It is NOT a stand alone language it must be used within Oracle. How PL/SQL works in comparison to other systems: In the first case we might have a number of SQL statements embedded in Java or PHP. This works but is not that efficient. In the second case, you can send a block of SQL statements to be executed like a program. More efficient. RPC is a protocol which allows a program running on one host to cause code to be executed on another host without the programmer needing to explicitly code for this. There are many variations and protocols, usually incompatible. Often used by hackers! We will not be looking at this. Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block. A block is the most important element in PL/SQL. 31

32 A PL/SQL Block consists of three sections: The Declaration section (optional). The Execution section (mandatory). The Exception (or Error) Handling section (optional). Declaration Section: The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE. This section is optional and is used to declare any placeholders like variables, constants, records and cursors, which are used to manipulate data in the execution section. Placeholders may be any of Variables, Constants and Records, which stores data temporarily. Cursors are also declared in this section. Execution Section: The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends with END. This is a mandatory section and is the section where the program logic is written to perform any task. The programmatic constructs like loops, conditional statement and SQL statements form the part of execution section. Exception Section: The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This section is optional. Any errors in the program can be handled in this section, so that the PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that cannot be handled, the Block terminates abruptly with errors. Every statement in the above three sections must end with a semicolon ;. PL/SQL blocks can be nested within other PL/SQL blocks. Comments can be used to document code. This is how a sample PL/SQL Block looks. Only the execution section is mandatory! DECLARE Variable declaration BEGIN Program Execution EXCEPTION Exception handling END; 32

33 Advantages of PL/SQL These are the advantages of PL/SQL. Block Structures: PL SQL consists of blocks of code, which can be nested within each other. Each block forms a unit of a task or a logical module. PL/SQL Blocks can be stored in the database and reused. Procedural Language Capability: PL SQL consists of procedural language constructs such as conditional statements (if else statements) and loops like (FOR loops). Better Performance: PL SQL engine processes multiple SQL statements simultaneously as a single block, thereby reducing network traffic. Error Handling: PL/SQL handles errors or exceptions effectively during the execution of a PL/SQL program. Once an exception is caught, specific actions can be taken depending upon the type of the exception or it can be displayed to the user with a message. Example: a very simple unnamed (anonymous) block that only contains an execution section. Note that to see the output on the screen you must enter set serveroutput on; The / executes the code. The block begins and ends with the kewords BEGIN and END; SQL> set serveroutput on; (pq1) SQL> begin 2 dbms_output.put_line ('Hello World'); 3 end; 4 / Hello World PL/SQL procedure successfully completed. 33

34 How to save and reuse your block: SQL> save pq1 (pq2) Wrote file pq1.sql SQL> get pq1 1 begin 2 dbms_output.put_line ('Hello World'); 3* end; 4 / Hello World PL/SQL procedure successfully completed. Note works just as well as get! Example: an unnamed block with a declaration section. Note that if a block is named it can be put into another block by name - no recoding required! The declare section begins with the keyword DECLARE. In this section you declare the variables to be used in the execution section. They must be unique variable names. The convention is if the attribute name is first_name then the variable name is v_first_name. It is always in the executable section between the BEGIN and END; part. 34

35 Q: Get/print the name of the student with id = 123. Also shows use of SELECT.INTO.FROM.WHERE construct. SQL> declare (pq3) 2 v_firstname varchar2(35); 3 v_lastname varchar2(35); 4 begin 5 select first_name, last_name 6 into v_firstname, v_lastname 7 from student 8 where student_id = 123; 9 dbms_output.put_line ('Student name is ' v_firstname ' ' v_lastname); 10 end; 11 / Student name is Pierre Radicola PL/SQL procedure successfully completed. SQL> 35

36 Runtime errors occur so that is when we use the exception handling section. SQL> declare (pq4) 2 v_firstname varchar2(35); 3 v_lastname varchar2(35); 4 begin 5 select first_name, last_name 6 into v_firstname, v_lastname 7 from student 8 where student_id = 1230; 9 dbms_output.put_line ('Student name is ' v_firstname ' ' v_lastname); 10 exception 11 when no_data_found then 12 dbms_output.put_line ('There is no student with id = 1230'); 13 end; There is no student with id = 1230 PL/SQL procedure successfully completed. 36

37 Q: Get the name and count the number of courses taught by instructor 102. (Could also use conventional join as in from where.) SQL> declare (pq5) 2 v_name varchar2(50); 3 v_total number; 4 begin 5 select i.first_name ' ' i.last_name, count(*) 6 into v_name, v_total 7 from instructor i 8 join section s 9 on (i.instructor_id = s.instructor_id) 10 where i.instructor_id = group by i.first_name ' ' i.last_name; 12 dbms_output.put_line (' Instructor ' v_name ' teaches ' v_total ' courses'); 13 exception 14 when no_data_found then 15 dbms_output.put_line ('There is no such instructor'); 16 end; Instructor Tom Wojick teaches 10 courses PL/SQL procedure successfully completed. 37

38 Substitution Variables: used when you want PL/SQL to provide a value to the block. Q: Get the names of various students based on the PK student_id SQL> declare (pq6) 2 v_student_id Number := &sv_student_id; 3 v_firstname varchar2(35); 4 v_lastname varchar2(35); 5 begin 6 select first_name, last_name 7 into v_firstname, v_lastname 8 from student 9 where student_id = v_student_id; 10 dbms_output.put_line ('Student name is ' v_firstname ' ' v_lastname); 11 exception 12 when no_data_found then 13 dbms_output.put_line ('There is no such student'); 14 end; 15 / Enter value for sv_student_id: 244 old 2: v_student_id Number := &sv_student_id; new 2: v_student_id Number := 244; Student name is Sarah Wilson PL/SQL procedure successfully completed. 38

39 Can be used again shows what happens when we enter a student id that does not exist. SQL> / (pq6) Enter value for sv_student_id: 2000 old 2: v_student_id Number := &sv_student_id; new 2: v_student_id Number := 2000; There is no such student PL/SQL procedure successfully completed. Another example of the use of substitute variables: SQL> begin (pq7) 2 dbms_output.put_line ('Today is ' '&sv_day'); 3 dbms_output.put_line ('Tomorrow is ' '&sv_day'); 4* end; Enter value for sv_day: Tuesday old 2: dbms_output.put_line ('Today is ' '&sv_day'); new 2: dbms_output.put_line ('Today is ' 'Tuesday'); Enter value for sv_day: Wednesday old 3: dbms_output.put_line ('Tomorrow is ' '&sv_day'); new 3: dbms_output.put_line ('Tomorrow is ' 'Wednesday'); Today is Tuesday Tomorrow is Wednesday PL/SQL procedure successfully completed. 39

40 Somewhat better. SQL> SET VERIFY OFF; (pq7a) Enter value for sv_day: Monday Enter value for sv_day: Tuesday Today is Monday OR. Tomorrow will be Tuesday SQL> run (pq8) 1 begin 2 dbms_output.put_line ('Today is ' '&&sv_day'); 3 dbms_output.put_line ('Tomorrow is ' '&sv_ day'); 4* end; old 2: dbms_output.put_line ('Today is ' '&&sv_day'); new 2: dbms_output.put_line ('Today is ' 'monday'); Enter value for sv_: Tuesday old 3: dbms_output.put_line ('Tomorrow is ' '&sv_ day'); new 3: dbms_output.put_line ('Tomorrow is ' 'Tuesday day'); Today is monday Tomorrow is Tuesday day This shows that PL/SQL can be extremely annoying!!!!! With && it retains the value. You can t put two && s in a block - it just gives them both the same value. I don t know what is happening with the Tuesday day output! Debugging code is difficult! 40

41 Getting today from the system: SQL> DECLARE (pq8a) v_day VARCHAR2(20); BEGIN v_day := TO_CHAR(SYSDATE, 'Day'); DBMS_OUTPUT.PUT_LINE ('Today is ' v_day); END; Today is Thursday Getting day and time from the system: SQL> DECLARE (pq8b) v_day VARCHAR2(20); BEGIN v_day := TO_CHAR(SYSDATE, 'Day, HH24:MI'); DBMS_OUTPUT.PUT_LINE ('Today is ' v_day); END; Today is Thursday, 14:42 PL/SQL procedure successfully completed. 41

42 Declaring and Initializing Variables: gives values to declared variables. The value given to the variable can be changed within a block. Variables declared as CONSTANT will NOT change. Example: SQL> run (pq9) 1 declare 2 v_cookies_amount number:=2; 3 v_calories_per_cookie Constant number := 300; 4 begin 5 dbms_output.put_line ('I ate ' v_cookies_amount ' cookies with ' v_cookies_amount * v_calories_per_cookie ' calories. '); 6 v_cookies_amount := 4; 7 dbms_output.put_line ('I really ate ' v_cookies_amount ' cookies with ' v_cookies_amount * v_calories_per_cookie ' calories. '); 8 dbms_output.put_line (' The truth is I really ate the whole bag of cookies. '); 9* end; I ate 2 cookies with 600 calories. I really ate 4 cookies with 1200 calories. The truth is I really ate the whole bag of cookies. PL/SQL procedure successfully completed. 42

43 Anchored data types: use if you are not sure of the data type of an attribute in the schema or if the data type may change at some point in time. Simple example: SQL> declare (pq10) 2 v_firstname student.first_name%type; 3 v_lastname student.last_name%type; 4 begin 5 dbms_output.put_line (' No data selected. '); 6 end; 7 / No data selected. PL/SQL procedure successfully completed. The %TYPE anchors the data type of the declared variables to the date type of the attribute as declared in the schema. We will see more interesting use of %TYPE later on. 43

44 Labels and nested blocks: because we can nest blocks it is important to label them and understand the scope of variables. The following is an example of labelled and nested blocks. SQL> <<outer_block>> 2 declare 3 v_test number := 333; 4 begin 5 DBMS_OUTPUT.PUT_LINE ('Outer Block, v_test ' v_test); 6 <<inner_block>> 7 declare 8 v_test number := 555; 9 begin 10 DBMS_OUTPUT.PUT_LINE ('Inner Block, v_test ' v_test); 11 end inner_block; 12* end outer_block; Outer Block, v_test 333 Inner Block, v_test 555 PL/SQL procedure successfully completed. 44

Oracle Database 11g: SQL and PL/SQL Fundamentals

Oracle Database 11g: SQL and PL/SQL Fundamentals Oracle University Contact Us: +33 (0) 1 57 60 20 81 Oracle Database 11g: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn In this course, students learn the fundamentals of SQL and PL/SQL

More information

Relational Data Structure and Concepts. Structured Query Language (Part 1) The Entity Integrity Rules. Relational Data Structure and Concepts

Relational Data Structure and Concepts. Structured Query Language (Part 1) The Entity Integrity Rules. Relational Data Structure and Concepts Relational Data Structure and Concepts Structured Query Language (Part 1) Two-dimensional tables whose attributes values are atomic. At every row-and-column position within the table, there always exists

More information

Table of Contents. PDF created with FinePrint pdffactory Pro trial version

Table of Contents. PDF created with FinePrint pdffactory Pro trial version Table of Contents Course Description The SQL Course covers relational database principles and Oracle concepts, writing basic SQL statements, restricting and sorting data, and using single-row functions.

More information

UNIT II PL / SQL AND TRIGGERS

UNIT II PL / SQL AND TRIGGERS UNIT II PL / SQL AND 1 TRIGGERS TOPIC TO BE COVERED.. 2.1 Basics of PL / SQL 2.2 Datatypes 2.3 Advantages 2.4 Control Structures : Conditional, Iterative, Sequential 2.5 Exceptions: Predefined Exceptions,User

More information

OVERVIEW OF THE TYPES OF PL/SQL BLOCKS:

OVERVIEW OF THE TYPES OF PL/SQL BLOCKS: OVERVIEW OF THE TYPES OF PL/SQL BLOCKS: The P/L SQL blocks can be divided into two broad categories: Anonymous Block: The anonymous block is the simplest unit in PL/SQL. It is called anonymous block because

More information

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: SQL and PL/SQL Fundamentals NEW Oracle Database: SQL and PL/SQL Fundamentals NEW Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training delivers the fundamentals of SQL and PL/SQL along with the

More information

Oracle Database: SQL and PL/SQL Fundamentals Ed 2

Oracle Database: SQL and PL/SQL Fundamentals Ed 2 Oracle University Contact Us: Local: 1800 103 4775 Intl: +91 80 67863102 Oracle Database: SQL and PL/SQL Fundamentals Ed 2 Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals

More information

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept] Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept] 1. What is DBMS? A Database Management System (DBMS) is a program that controls creation, maintenance and use

More information

5. Single-row function

5. Single-row function 1. 2. Introduction Oracle 11g Oracle 11g Application Server Oracle database Relational and Object Relational Database Management system Oracle internet platform System Development Life cycle 3. Writing

More information

SQL Interview Questions

SQL Interview Questions SQL Interview Questions SQL stands for Structured Query Language. It is used as a programming language for querying Relational Database Management Systems. In this tutorial, we shall go through the basic

More information

Oracle Database 10g: Introduction to SQL

Oracle Database 10g: Introduction to SQL ORACLE UNIVERSITY CONTACT US: 00 9714 390 9000 Oracle Database 10g: Introduction to SQL Duration: 5 Days What you will learn This course offers students an introduction to Oracle Database 10g database

More information

1) Introduction to SQL

1) Introduction to SQL 1) Introduction to SQL a) Database language enables users to: i) Create the database and relation structure; ii) Perform insertion, modification and deletion of data from the relationship; and iii) Perform

More information

12. MS Access Tables, Relationships, and Queries

12. MS Access Tables, Relationships, and Queries 12. MS Access Tables, Relationships, and Queries 12.1 Creating Tables and Relationships Suppose we want to build a database to hold the information for computers (also refer to parts in the text) and suppliers

More information

Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL

Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL Chapter 3: Introduction to SQL Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Chapter 3: Introduction to SQL Overview of The SQL Query Language Data Definition Basic Query

More information

Sql Server Syllabus. Overview

Sql Server Syllabus. Overview Sql Server Syllabus Overview This SQL Server training teaches developers all the Transact-SQL skills they need to create database objects like Tables, Views, Stored procedures & Functions and triggers

More information

UNIT-IV (Relational Database Language, PL/SQL)

UNIT-IV (Relational Database Language, PL/SQL) UNIT-IV (Relational Database Language, PL/SQL) Section-A (2 Marks) Important questions 1. Define (i) Primary Key (ii) Foreign Key (iii) unique key. (i)primary key:a primary key can consist of one or more

More information

UFCEKG 20 2 : Data, Schemas and Applications

UFCEKG 20 2 : Data, Schemas and Applications Lecture 11 UFCEKG 20 2 : Data, Schemas and Applications Lecture 11 Database Theory & Practice (5) : Introduction to the Structured Query Language (SQL) Origins & history Early 1970 s IBM develops Sequel

More information

Principles of Data Management

Principles of Data Management Principles of Data Management Alvin Lin August 2018 - December 2018 Structured Query Language Structured Query Language (SQL) was created at IBM in the 80s: SQL-86 (first standard) SQL-89 SQL-92 (what

More information

EE221 Databases Practicals Manual

EE221 Databases Practicals Manual EE221 Databases Practicals Manual Lab 1 An Introduction to SQL Lab 2 Database Creation and Querying using SQL Assignment Data Analysis, Database Design, Implementation and Relation Normalisation School

More information

CIS 330: Applied Database Systems

CIS 330: Applied Database Systems 1 CIS 330: Applied Database Systems Lecture 7: SQL Johannes Gehrke johannes@cs.cornell.edu http://www.cs.cornell.edu/johannes Logistics Office hours role call: Mondays, 3-4pm Tuesdays, 4:30-5:30 Wednesdays,

More information

Jarek Szlichta

Jarek Szlichta Jarek Szlichta http://data.science.uoit.ca/ SQL is a standard language for accessing and manipulating databases What is SQL? SQL stands for Structured Query Language SQL lets you gain access and control

More information

The SQL data-definition language (DDL) allows defining :

The SQL data-definition language (DDL) allows defining : Introduction to SQL Introduction to SQL Overview of the SQL Query Language Data Definition Basic Query Structure Additional Basic Operations Set Operations Null Values Aggregate Functions Nested Subqueries

More information

The PL/SQL Engine: PL/SQL. A PL/SQL Block: Declaration Section. Execution Section. Declaration Section 3/24/2014

The PL/SQL Engine: PL/SQL. A PL/SQL Block: Declaration Section. Execution Section. Declaration Section 3/24/2014 PL/SQL The PL/SQL Engine: PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle

More information

Part I: Structured Data

Part I: Structured Data Inf1-DA 2011 2012 I: 92 / 117 Part I Structured Data Data Representation: I.1 The entity-relationship (ER) data model I.2 The relational model Data Manipulation: I.3 Relational algebra I.4 Tuple-relational

More information

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables INDEX Exercise No Title 1 Basic SQL Statements 2 Restricting and Sorting Data 3 Single Row Functions 4 Displaying data from multiple tables 5 Creating and Managing Tables 6 Including Constraints 7 Manipulating

More information

SQL STRUCTURED QUERY LANGUAGE

SQL STRUCTURED QUERY LANGUAGE STRUCTURED QUERY LANGUAGE SQL Structured Query Language 4.1 Introduction Originally, SQL was called SEQUEL (for Structured English QUery Language) and implemented at IBM Research as the interface for an

More information

Oracle Syllabus Course code-r10605 SQL

Oracle Syllabus Course code-r10605 SQL Oracle Syllabus Course code-r10605 SQL Writing Basic SQL SELECT Statements Basic SELECT Statement Selecting All Columns Selecting Specific Columns Writing SQL Statements Column Heading Defaults Arithmetic

More information

Chapter 3: Introduction to SQL

Chapter 3: Introduction to SQL Chapter 3: Introduction to SQL Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Chapter 3: Introduction to SQL Overview of the SQL Query Language Data Definition Basic Query

More information

Slides by: Ms. Shree Jaswal

Slides by: Ms. Shree Jaswal Slides by: Ms. Shree Jaswal Overview of SQL, Data Definition Commands, Set operations, aggregate function, null values, Data Manipulation commands, Data Control commands, Views in SQL, Complex Retrieval

More information

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13 CS121 MIDTERM REVIEW CS121: Relational Databases Fall 2017 Lecture 13 2 Before We Start Midterm Overview 3 6 hours, multiple sittings Open book, open notes, open lecture slides No collaboration Possible

More information

Chapter 3: Introduction to SQL

Chapter 3: Introduction to SQL Chapter 3: Introduction to SQL Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Chapter 3: Introduction to SQL Overview of the SQL Query Language Data Definition Basic Query

More information

ADVANTAGES. Via PL/SQL, all sorts of calculations can be done quickly and efficiently without use of Oracle engine.

ADVANTAGES. Via PL/SQL, all sorts of calculations can be done quickly and efficiently without use of Oracle engine. 1 PL/SQL INTRODUCTION SQL does not have procedural capabilities. SQL does not provide the programming techniques of condition checking, looping and branching that is required for data before permanent

More information

Relational Algebra and SQL

Relational Algebra and SQL Relational Algebra and SQL Computer Science E-66 Harvard University David G. Sullivan, Ph.D. Example Domain: a University We ll use relations from a university database. four relations that store info.

More information

Announcements (September 14) SQL: Part I SQL. Creating and dropping tables. Basic queries: SFW statement. Example: reading a table

Announcements (September 14) SQL: Part I SQL. Creating and dropping tables. Basic queries: SFW statement. Example: reading a table Announcements (September 14) 2 SQL: Part I Books should have arrived by now Homework #1 due next Tuesday Project milestone #1 due in 4 weeks CPS 116 Introduction to Database Systems SQL 3 Creating and

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe CHAPTER 6 Basic SQL Slide 6-2 Chapter 6 Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries in SQL INSERT, DELETE, and UPDATE Statements in SQL Additional Features

More information

T-SQL Training: T-SQL for SQL Server for Developers

T-SQL Training: T-SQL for SQL Server for Developers Duration: 3 days T-SQL Training Overview T-SQL for SQL Server for Developers training teaches developers all the Transact-SQL skills they need to develop queries and views, and manipulate data in a SQL

More information

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 6 Professional Program: Data Administration and Management MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9) AGENDA

More information

Where are we? Week -4: Data definition (Creation of the schema) Week -3: Data definition (Triggers) Week -1: Transactions and concurrency in ORACLE.

Where are we? Week -4: Data definition (Creation of the schema) Week -3: Data definition (Triggers) Week -1: Transactions and concurrency in ORACLE. Where are we? Week -4: Data definition (Creation of the schema) Week -3: Data definition (Triggers) Week -2: More SQL queries Week -1: Transactions and concurrency in ORACLE. But don t forget to work on

More information

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints SQL KEREM GURBEY WHAT IS SQL Database query language, which can also: Define structure of data Modify data Specify security constraints DATA DEFINITION Data-definition language (DDL) provides commands

More information

ORACLE Reference. 2. Modify your start-up script file using Option 1 or 2 below, depending on which shell you run.

ORACLE Reference. 2. Modify your start-up script file using Option 1 or 2 below, depending on which shell you run. ORACLE Reference 1 Introduction The ORACLE RDBMS is a relational database management system. A command language called SQL*PLUS (SQL stands for Structured Query Language ) is used for working with an OR-

More information

Oracle Database: Introduction to SQL Ed 2

Oracle Database: Introduction to SQL Ed 2 Oracle University Contact Us: +40 21 3678820 Oracle Database: Introduction to SQL Ed 2 Duration: 5 Days What you will learn This Oracle Database 12c: Introduction to SQL training helps you write subqueries,

More information

Data about data is database Select correct option: True False Partially True None of the Above

Data about data is database Select correct option: True False Partially True None of the Above Within a table, each primary key value. is a minimal super key is always the first field in each table must be numeric must be unique Foreign Key is A field in a table that matches a key field in another

More information

INFSCI 2710 Database Management Solution to Final Exam

INFSCI 2710 Database Management Solution to Final Exam Dr. Stefan Brass May 8, 2000 School of Information Sciences University of Pittsburgh INFSCI 2710 Database Management Solution to Final Exam Statistics The average points reached (out of 42) were 32 (77%),

More information

Lesson 2. Data Manipulation Language

Lesson 2. Data Manipulation Language Lesson 2 Data Manipulation Language IN THIS LESSON YOU WILL LEARN To add data to the database. To remove data. To update existing data. To retrieve the information from the database that fulfil the stablished

More information

Introduction to Computer Science and Business

Introduction to Computer Science and Business Introduction to Computer Science and Business This is the second portion of the Database Design and Programming with SQL course. In this portion, students implement their database design by creating a

More information

Exam code: Exam name: Database Fundamentals. Version 16.0

Exam code: Exam name: Database Fundamentals. Version 16.0 98-364 Number: 98-364 Passing Score: 800 Time Limit: 120 min File Version: 16.0 Exam code: 98-364 Exam name: Database Fundamentals Version 16.0 98-364 QUESTION 1 You have a table that contains the following

More information

Database design process

Database design process Database technology Lecture 2: Relational databases and SQL Jose M. Peña jose.m.pena@liu.se Database design process 1 Relational model concepts... Attributes... EMPLOYEE FNAME M LNAME SSN BDATE ADDRESS

More information

Database Management Systems,

Database Management Systems, Database Management Systems SQL Query Language (3) 1 Topics Aggregate Functions in Queries count sum max min avg Group by queries Set Operations in SQL Queries Views 2 Aggregate Functions Tables are collections

More information

CSC Web Programming. Introduction to SQL

CSC Web Programming. Introduction to SQL CSC 242 - Web Programming Introduction to SQL SQL Statements Data Definition Language CREATE ALTER DROP Data Manipulation Language INSERT UPDATE DELETE Data Query Language SELECT SQL statements end with

More information

DB2 SQL Class Outline

DB2 SQL Class Outline DB2 SQL Class Outline The Basics of SQL Introduction Finding Your Current Schema Setting Your Default SCHEMA SELECT * (All Columns) in a Table SELECT Specific Columns in a Table Commas in the Front or

More information

Computing for Medicine (C4M) Seminar 3: Databases. Michelle Craig Associate Professor, Teaching Stream

Computing for Medicine (C4M) Seminar 3: Databases. Michelle Craig Associate Professor, Teaching Stream Computing for Medicine (C4M) Seminar 3: Databases Michelle Craig Associate Professor, Teaching Stream mcraig@cs.toronto.edu Relational Model The relational model is based on the concept of a relation or

More information

CSEN 501 CSEN501 - Databases I

CSEN 501 CSEN501 - Databases I CSEN501 - Databases I Lecture 5: Structured Query Language (SQL) Prof. Dr. Slim slim.abdennadher@guc.edu.eg German University Cairo, Faculty of Media Engineering and Technology Structured Query Language:

More information

Table of Contents. Oracle SQL PL/SQL Training Courses

Table of Contents. Oracle SQL PL/SQL Training Courses Table of Contents Overview... 7 About DBA University, Inc.... 7 Eligibility... 8 Pricing... 8 Course Topics... 8 Relational database design... 8 1.1. Computer Database Concepts... 9 1.2. Relational Database

More information

You can write a command to retrieve specified columns and all rows from a table, as illustrated

You can write a command to retrieve specified columns and all rows from a table, as illustrated CHAPTER 4 S I N G L E - TA BL E QUERIES LEARNING OBJECTIVES Objectives Retrieve data from a database using SQL commands Use simple and compound conditions in queries Use the BETWEEN, LIKE, and IN operators

More information

Querying Data with Transact-SQL

Querying Data with Transact-SQL Querying Data with Transact-SQL Course: 20761 Course Details Audience(s): IT Professional(s) Technology: Microsoft SQL Server 2016 Duration: 24 HRs. ABOUT THIS COURSE This course is designed to introduce

More information

CIS Slightly-different version of Week 10 Lab, also intro to SQL UPDATE and DELETE, and more

CIS Slightly-different version of Week 10 Lab, also intro to SQL UPDATE and DELETE, and more CIS 315 - Week 10 Lab Exercise p. 1 Sources: CIS 315 - Slightly-different version of Week 10 Lab, 10-27-09 more SELECT operations: UNION, INTERSECT, and MINUS, also intro to SQL UPDATE and DELETE, and

More information

Querying Data with Transact SQL

Querying Data with Transact SQL Course 20761A: Querying Data with Transact SQL Course details Course Outline Module 1: Introduction to Microsoft SQL Server 2016 This module introduces SQL Server, the versions of SQL Server, including

More information

Sankalchand Patel College of Engineering, Visnagar B.E. Semester III (CE/IT) Database Management System Question Bank / Assignment

Sankalchand Patel College of Engineering, Visnagar B.E. Semester III (CE/IT) Database Management System Question Bank / Assignment Sankalchand Patel College of Engineering, Visnagar B.E. Semester III (CE/IT) Database Management System Question Bank / Assignment Introductory concepts of DBMS 1. Explain detailed 3-level architecture

More information

Semantic Errors in Database Queries

Semantic Errors in Database Queries Semantic Errors in Database Queries 1 Semantic Errors in Database Queries Stefan Brass TU Clausthal, Germany From April: University of Halle, Germany Semantic Errors in Database Queries 2 Classification

More information

Students Guide. Requirements of your homework

Students Guide. Requirements of your homework Students Guide Requirements of your homework During the SQL labs you should create SQL scripts, which correspond to the SQL script skeleton provided. In the case of the SQL1 lab, you should also hand in

More information

SQL Data Query Language

SQL Data Query Language SQL Data Query Language André Restivo 1 / 68 Index Introduction Selecting Data Choosing Columns Filtering Rows Set Operators Joining Tables Aggregating Data Sorting Rows Limiting Data Text Operators Nested

More information

An Introduction to Structured Query Language

An Introduction to Structured Query Language An Introduction to Structured Query Language Grant Weddell Cheriton School of Computer Science University of Waterloo CS 348 Introduction to Database Management Winter 2017 CS 348 (Intro to DB Mgmt) SQL

More information

Announcements (September 18) SQL: Part II. Solution 1. Incomplete information. Solution 3? Solution 2. Homework #1 due today (11:59pm)

Announcements (September 18) SQL: Part II. Solution 1. Incomplete information. Solution 3? Solution 2. Homework #1 due today (11:59pm) Announcements (September 18) 2 SQL: Part II Homework #1 due today (11:59pm) Submit in class, slide underneath my office door Sample solution available Thursday Homework #2 assigned today CPS 116 Introduction

More information

CPS 216 Spring 2003 Homework #1 Assigned: Wednesday, January 22 Due: Monday, February 10

CPS 216 Spring 2003 Homework #1 Assigned: Wednesday, January 22 Due: Monday, February 10 CPS 216 Spring 2003 Homework #1 Assigned: Wednesday, January 22 Due: Monday, February 10 Note: This is a long homework. Start early! If you have already taken CPS 196.3 or an equivalent undergraduate course

More information

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals Oracle University Contact Us: 001-855-844-3881 & 001-800-514-06-9 7 Oracle Database: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training

More information

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E)

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E) 1 NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E) 2 LECTURE OUTLINE More Complex SQL Retrieval Queries Self-Joins Renaming Attributes and Results Grouping, Aggregation, and Group Filtering

More information

An Introduction to Structured Query Language

An Introduction to Structured Query Language An Introduction to Structured Query Language Grant Weddell Cheriton School of Computer Science University of Waterloo CS 348 Introduction to Database Management Spring 2016 CS 348 (Intro to DB Mgmt) SQL

More information

Database Languages. A DBMS provides two types of languages: Language for accessing & manipulating the data. Language for defining a database schema

Database Languages. A DBMS provides two types of languages: Language for accessing & manipulating the data. Language for defining a database schema SQL 1 Database Languages A DBMS provides two types of languages: DDL Data Definition Language Language for defining a database schema DML Data Manipulation Language Language for accessing & manipulating

More information

An Introduction to Structured Query Language

An Introduction to Structured Query Language An Introduction to Structured Query Language Grant Weddell David R. Cheriton School of Computer Science University of Waterloo CS 348 Introduction to Database Management Spring 2012 CS 348 (Intro to DB

More information

NULLs & Outer Joins. Objectives of the Lecture :

NULLs & Outer Joins. Objectives of the Lecture : Slide 1 NULLs & Outer Joins Objectives of the Lecture : To consider the use of NULLs in SQL. To consider Outer Join Operations, and their implementation in SQL. Slide 2 Missing Values : Possible Strategies

More information

An Introduction to Structured Query Language

An Introduction to Structured Query Language An Introduction to Structured Query Language Grant Weddell David R. Cheriton School of Computer Science University of Waterloo CS 348 Introduction to Database Management Spring 2012 CS 348 (Intro to DB

More information

2 PL/SQL - fundamentals Variables and Constants Operators SQL in PL/SQL Control structures... 7

2 PL/SQL - fundamentals Variables and Constants Operators SQL in PL/SQL Control structures... 7 Table of Contents Spis treści 1 Introduction 1 2 PLSQL - fundamentals 1 2.1 Variables and Constants............................ 2 2.2 Operators.................................... 5 2.3 SQL in PLSQL.................................

More information

SQL: Part II. Announcements (September 18) Incomplete information. CPS 116 Introduction to Database Systems. Homework #1 due today (11:59pm)

SQL: Part II. Announcements (September 18) Incomplete information. CPS 116 Introduction to Database Systems. Homework #1 due today (11:59pm) SQL: Part II CPS 116 Introduction to Database Systems Announcements (September 18) 2 Homework #1 due today (11:59pm) Submit in class, slide underneath my office door Sample solution available Thursday

More information

Using the Set Operators. Copyright 2006, Oracle. All rights reserved.

Using the Set Operators. Copyright 2006, Oracle. All rights reserved. Using the Set Operators Objectives After completing this lesson, you should be able to do the following: Describe set operators Use a set operator to combine multiple queries into a single query Control

More information

CSE 544 Principles of Database Management Systems

CSE 544 Principles of Database Management Systems CSE 544 Principles of Database Management Systems Lecture 1 - Introduction and the Relational Model 1 Outline Introduction Class overview Why database management systems (DBMS)? The relational model 2

More information

Course Outline and Objectives: Database Programming with SQL

Course Outline and Objectives: Database Programming with SQL Introduction to Computer Science and Business Course Outline and Objectives: Database Programming with SQL This is the second portion of the Database Design and Programming with SQL course. In this portion,

More information

Introduction. Sample Database SQL-92. Sample Data. Sample Data. Chapter 6 Introduction to Structured Query Language (SQL)

Introduction. Sample Database SQL-92. Sample Data. Sample Data. Chapter 6 Introduction to Structured Query Language (SQL) Chapter 6 Introduction to Structured Query Language (SQL) Introduction Structured Query Language (SQL) is a data sublanguage that has constructs for defining and processing a database It can be Used stand-alone

More information

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data 1 Writing Basic SQL SELECT Statements Objectives 1-2 Capabilities of SQL SELECT Statements 1-3 Basic SELECT Statement 1-4 Selecting All Columns 1-5 Selecting Specific Columns 1-6 Writing SQL Statements

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe CHAPTER 7 More SQL: Complex Queries, Triggers, Views, and Schema Modification Slide 7-2 Chapter 7 Outline More Complex SQL Retrieval Queries Specifying Semantic Constraints as Assertions and Actions as

More information

Lab # 6. Using Subqueries and Set Operators. Eng. Alaa O Shama

Lab # 6. Using Subqueries and Set Operators. Eng. Alaa O Shama The Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4113: Database Lab Lab # 6 Using Subqueries and Set Operators Eng. Alaa O Shama November, 2015 Objectives:

More information

Index. Bitmap Heap Scan, 156 Bitmap Index Scan, 156. Rahul Batra 2018 R. Batra, SQL Primer,

Index. Bitmap Heap Scan, 156 Bitmap Index Scan, 156. Rahul Batra 2018 R. Batra, SQL Primer, A Access control, 165 granting privileges to users general syntax, GRANT, 170 multiple privileges, 171 PostgreSQL, 166 169 relational databases, 165 REVOKE command, 172 173 SQLite, 166 Aggregate functions

More information

Instructor: Craig Duckett. Lecture 11: Thursday, May 3 th, Set Operations, Subqueries, Views

Instructor: Craig Duckett. Lecture 11: Thursday, May 3 th, Set Operations, Subqueries, Views Instructor: Craig Duckett Lecture 11: Thursday, May 3 th, 2018 Set Operations, Subqueries, Views 1 MID-TERM EXAM GRADED! Assignment 2 is due LECTURE 12, NEXT Tuesday, May 8 th in StudentTracker by MIDNIGHT

More information

2. Software Oracle 12c is installed on departmental server machines.

2. Software Oracle 12c is installed on departmental server machines. 1. Introduction This note describes how to access the Oracle database management system on the departmental computer systems. Basic information on the use of SQL*Plus is included. Section 8 tells you how

More information

SQL for MySQL A Beginner s Tutorial

SQL for MySQL A Beginner s Tutorial SQL for MySQL A Beginner s Tutorial Djoni Darmawikarta SQL for MySQL: A Beginner s Tutorial Copyright 2014 Brainy Software Inc. First Edition: June 2014 All rights reserved. No part of this book may be

More information

SQL. Chapter 5 FROM WHERE

SQL. Chapter 5 FROM WHERE SQL Chapter 5 Instructor: Vladimir Zadorozhny vladimir@sis.pitt.edu Information Science Program School of Information Sciences, University of Pittsburgh 1 Basic SQL Query SELECT FROM WHERE [DISTINCT] target-list

More information

Oracle SQL & PL SQL Course

Oracle SQL & PL SQL Course Oracle SQL & PL SQL Course Complete Practical & Real-time Training Job Support Complete Practical Real-Time Scenarios Resume Preparation Lab Access Training Highlights Placement Support Support Certification

More information

SQL Part 3: Where Subqueries and other Syntactic Sugar Part 4: Unknown Values and NULLs

SQL Part 3: Where Subqueries and other Syntactic Sugar Part 4: Unknown Values and NULLs SQL Part 3: Where Subqueries and other Syntactic Sugar Part 4: Unknown Values and NULLs 1-1 List of Slides 1 2 More on "where" conditions 3 Esoteric Predicates: Example 4 WHERE Subqueries 5 Overview of

More information

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries

More information

Procedural Language Structured Query Language (PL/SQL)

Procedural Language Structured Query Language (PL/SQL) The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Database Lab (ECOM 4113) Lab 7 Procedural Language Structured Query Language (PL/SQL) Eng. Ibraheem Lubbad Structured

More information

Oracle Database 11g: SQL Fundamentals I

Oracle Database 11g: SQL Fundamentals I Oracle Database 11g: SQL Fundamentals I Volume I Student Guide D49996GC11 Edition 1.1 April 2009 D59980 Authors Puja Singh Brian Pottle Technical Contributors and Reviewers Claire Bennett Tom Best Purjanti

More information

SQL: Data Manipulation Language. csc343, Introduction to Databases Diane Horton Winter 2017

SQL: Data Manipulation Language. csc343, Introduction to Databases Diane Horton Winter 2017 SQL: Data Manipulation Language csc343, Introduction to Databases Diane Horton Winter 2017 Introduction So far, we have defined database schemas and queries mathematically. SQL is a formal language for

More information

An Introduction to Structured Query Language

An Introduction to Structured Query Language An Introduction to Structured Query Language Alexandra Roatiş David R. Cheriton School of Computer Science University of Waterloo CS 348 Introduction to Database Management Winter 2016 CS 348 SQL Winter

More information

Tables From Existing Tables

Tables From Existing Tables Creating Tables From Existing Tables After completing this module, you will be able to: Create a clone of an existing table. Create a new table from many tables using a SQL SELECT. Define your own table

More information

SQL: csc343, Introduction to Databases Renée J. Miller and Fatemeh Nargesian and Sina Sina Meraji. Winter 2018

SQL: csc343, Introduction to Databases Renée J. Miller and Fatemeh Nargesian and Sina Sina Meraji. Winter 2018 SQL: csc343, Introduction to Databases Renée J. Miller and Fatemeh Nargesian and Sina Sina Meraji Winter 2018 Introduction So far, we have defined database schemas and queries mathematically. SQL is a

More information

Database Technology. Topic 3: SQL. Olaf Hartig.

Database Technology. Topic 3: SQL. Olaf Hartig. Olaf Hartig olaf.hartig@liu.se Structured Query Language Declarative language (what data to get, not how) Considered one of the major reasons for the commercial success of relational databases Statements

More information

Agenda. Discussion. Database/Relation/Tuple. Schema. Instance. CSE 444: Database Internals. Review Relational Model

Agenda. Discussion. Database/Relation/Tuple. Schema. Instance. CSE 444: Database Internals. Review Relational Model Agenda CSE 444: Database Internals Review Relational Model Lecture 2 Review of the Relational Model Review Queries (will skip most slides) Relational Algebra SQL Review translation SQL à RA Needed for

More information

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No. Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No. # 5 Structured Query Language Hello and greetings. In the ongoing

More information

Database Programming with SQL

Database Programming with SQL Database Programming with SQL 2-1 Objectives This lesson covers the following objectives: Apply the concatenation operator to link columns to other columns, arithmetic expressions, or constant values to

More information

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement Chapter 4 Basic SQL Basic SQL SQL language Considered one of the major reasons for the commercial success of relational databases SQL Structured Query Language Statements for data definitions, queries,

More information

Relational Model History. COSC 416 NoSQL Databases. Relational Model (Review) Relation Example. Relational Model Definitions. Relational Integrity

Relational Model History. COSC 416 NoSQL Databases. Relational Model (Review) Relation Example. Relational Model Definitions. Relational Integrity COSC 416 NoSQL Databases Relational Model (Review) Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Relational Model History The relational model was proposed by E. F. Codd

More information