Download presentation
Presentation is loading. Please wait.
1
SQL Primer SQL Primer ©SoftMoore Consulting
2
SQL Overview Text-based query language developed by IBM for an experimental RDBMS called System R originally called SEQUEL Most widely supported query language among commercial RDBMS products although no one supports the standard exactly Uses the more informal terms table, row, and column in place of relation, tuple, and attribute Declarative, not procedural Large, comprehensive database language reference document is over 600 pages long ©SoftMoore Consulting
3
ANSI/ISO Standardization
Year Name Comment 1986 SQL-86 Initial standard 1989 SQL-89 Minor revision 1992 SQL-92 (a.k.a. SQL2) Major revision (ISO 9075) 1999 SQL:1999 (a.k.a. SQL3) Added regular expressions, recursive queries, triggers, non-scalar types, some O-O features. 2003 SQL:2003 Introduced XML-related features and auto-generated column values. 2006 SQL:2006 Defined ways of importing and storing XML data. 2008 SQL:2008 Added INSTEAD OF triggers and TRUNCATE statement. 2011 SQL:2011 Added temporal data definition and manipulation. ©SoftMoore Consulting
4
SQL Data Types Boolean and Bit String Types Character types
SQL Primer SQL Data Types Boolean and Bit String Types boolean : can be true, false, or null bit(n) : n-length bit string (exactly n binary bits) bit varying(n), varbit(n) : variable n-length bit string (up to n binary bits) Character types character (n), char(n) : fixed n-length character string character varying(n), varchar(n) : variable length character string of up to n characters national character(n) or nchar(n) : fixed n-length string supporting an international character set national character varying(n) or nvarchar(n) : variable length string supporting an international character set no longer part of SQL standard ©SoftMoore Consulting
5
SQL Data Types Numeric types Date and time types
SQL Primer SQL Data Types Numeric types smallint : signed 2-byte integer integer, int : signed 4-byte integer real, float : 4-byte floating-point number double precision : 8-byte floating-point number numeric(p, s), decimal(p, s) : an exact numeric type with arbitrary precision p and scale s Date and time types date : calendar date (day, month, and year) time : time of day timestamp (includes time zone) : both the date and time interval : an arbitrarily specified length of time ©SoftMoore Consulting
6
SQL Data Types Large Objects
SQL Primer SQL Data Types Large Objects BLOB (binary large object): variable sized binary object with no size constraint (maximum size is 2 billion bytes) CLOB (character large object) : string of variable length without a size constraint (maximum size is 1 billion characters) ©SoftMoore Consulting
7
Using SQL Data Types in the Real World
SQL Primer Using SQL Data Types in the Real World Warning: The actual data types and type names differ greatly among the individual RDBMS implementations. Examples Data Type SQL Standard Oracle MS Access DECIMAL yes no CURRENCY NUMBER ©SoftMoore Consulting
8
Writing SQL Statements
SQL Primer Writing SQL Statements Free format SQL commands not case sensitive – string literals are Commas separate items in a list Period separates table name and column name Comment lines begin with double dash (--) Single quotes around string literals Access also allows double quotes Semicolon marks the end of a statement String concatenation uses | sometimes shows up as ¦ ©SoftMoore Consulting
9
SQL Primer SQL Queries ©SoftMoore Consulting
10
Retrieving Data from Tables: The SELECT Statement
SQL Primer Retrieving Data from Tables: The SELECT Statement SQL uses the SELECT statement (with many options and variations) as the primary statement for data retrieval. Basic format: select <columns> from <tables> where <conditions> order by <sort columns>; Example select name, phone from customer; select name, phone from customer where area_code = '843'; ©SoftMoore Consulting
11
SQL Primer Duplicates By default, SQL does not eliminate duplicate rows from the result of a SELECT statement. The user may explicitly request that duplicate rows be eliminated by using the keyword DISTINCT as part of the request. select distinct state from customer; ©SoftMoore Consulting
12
SQL Primer Conditions Conditions are specified within the WHERE clause of a SELECT statement. select * from orders where total_invoice > 1000; Note: “*” selects all columns. ©SoftMoore Consulting
13
Operators Used in Conditions
SQL Primer Operators Used in Conditions Parentheses for grouping Relational Operators = <> or != < > <= >= Logical Operators AND OR NOT Test Operators IN BETWEEN IS NULL IS NOT NULL Pattern Matching Operators LIKE (plus a pattern) _ matches single character (? for Access) % matches multiple characters (* for Access) ©SoftMoore Consulting
14
Examples: Queries on a Single Table
SQL Primer Examples: Queries on a Single Table select order_num, sale_date, ship_date, total_invoice from orders where total_invoice > 1000 order by total_invoice desc; select order_num, cust_num, total_invoice, amount_paid where amount_paid < total_invoice and total_invoice between 1000 and 2000; select * from customer where last_name like 'M%' order by last_name; ©SoftMoore Consulting
15
SQL Primer Compound Conditions The boolean operators AND and OR can be used to create compound conditions. Parentheses can be used for grouping Example select order_num, cust_num, ship_date, total_invoice from orders where (total_invoice > 1000 and amount_paid < 100) or amount_paid < 1; ©SoftMoore Consulting
16
Set Operators on Tables
SQL Primer Set Operators on Tables Set union – UNION Set difference – EXCEPT Set intersection – INTERSECT Example: (select name from customer where state = 'FL') union (select name from vendor where state = 'FL'); Note: The output of an SQL query is another table (closure property). ©SoftMoore Consulting
17
SQL Primer Joining Two Tables The join operation can be specified in terms of SELECT, FROM, and WHERE clauses. Attributes from different tables can be qualified by the table name. Example select customer.name, customer.phone, orders.total_invoice, orders.amount_paid from customer, orders where customer.cust_num = orders.cust_num and orders.amount_paid < orders.total_invoice; Alternate format using a table alias: select c.name, c.phone, o.total_invoice, o.amount_paid from customer c, orders o where c.cust_num = o.cust_num and o.amount_paid < o.total_invoice; ©SoftMoore Consulting
18
Comments on the Join Example
SQL Primer Comments on the Join Example The first condition in the where clause specifies the “join” condition. Table name qualification of attributes can be omitted when there is no ambiguity. ©SoftMoore Consulting
19
Alternate Syntax for Join
SQL Primer Alternate Syntax for Join A join could be specified more simply using the explicit INNER JOIN (keyword INNER can be omitted) or the NATURAL JOIN operator, which was added in SQL/92. select c.name, c.phone, o.total_invoice, o.amount_paid from customer c join orders o on c.cust_num = o.cust_num where o.amount_paid < o.total_invoice; from customer c natural join orders o where o.total_amount_paid < o.total_invoice; ©SoftMoore Consulting
20
More Complicated Queries
SQL Primer More Complicated Queries Complicated, multi-relation queries often involve combinations of tables, columns, and conditions. select c.name, c.phone from customer c, orders o, lineitem li where c.cust_num = o.cust_num and o.order_num = li.order_num and li.quantity > 5; Alternatively, we could express this query using the NATURAL JOIN operator. from customer c natural join orders o natural join lineitem li where li.quantity > 5; ©SoftMoore Consulting
21
Inner Joins When querying data from two or more tables using joins, most of the time you will want to use an inner join. All examples thus far have used inner joins. Example (inner join) select p.name, b.title from publisher p join book b on p.publisher_id = b.publisher_id; An inner join will include rows from a table only if there are matching rows in the joined table. In the above example, publishers will not be included if there are no books published by them in the book table. ©SoftMoore Consulting
22
Outer Joins To include all rows in a table whether or not there are matching rows in the other table, use an outer join. Example select p.name, b.title from publisher p left outer join book b on p.publisher_id = b.publisher_id; (Note: The word “outer” can be omitted from this query.) The above example will select all publishers, even if there are no corresponding books in the book table. Values for b.title will be null for publishers without corresponding books. ©SoftMoore Consulting
23
Outer Joins (continued)
Outer joins can be “left”, “right”, or “full”, where “full” includes values from both tables. Some database systems do not support full outer joins directly, but full outer joins can be simulated by using left and right outer joins and unions. (select p.name, b.title from publisher p left join book b on p.publisher_id = b.publisher_id) union from publisher p right join book b on p.publisher_id = b.publisher_id); ©SoftMoore Consulting
24
Subqueries A subquery can be used to select data involving two or more tables, but … the selected data can come only from the top-level table. Example select name from customer where cust_id in (select cust_id from orders where total_invoice > 1000); ©SoftMoore Consulting
25
Correlated Subqueries
A correlated subquery uses the same table in both levels of the query. The inner query is recomputed for each row in the outer query. Example select b1.title from book b1 where b1.title in (select b2.title from book b2 where b1.title = b2.title and b1.book_id <> b2.book_id); Finds different books (different IDs) with the same title. ©SoftMoore Consulting
26
EXISTS and NOT EXISTS EXISTS and NOT EXISTS are boolean operators that can be used in the “where” clause of correlated subqueries. General format: select columns from tables where exists (subquery); An EXISTS condition is true if any row in the subquery meets the specified conditions. A NOT EXISTS condition is true only if all rows in the subquery do not meet the specified condition/ ©SoftMoore Consulting
27
Example: Using the EXISTS Operator
Find the names of all publishers that publish a book on Java (i.e., has the word “Java” in the title). select name from publisher where exists (select * from book where book.publisher_id = publisher.publisher_id and book.title like '%Java%'); The above query is equivalent to the following: where publisher_id in (select publisher_id where book.title like '%Java%'); ©SoftMoore Consulting
28
Derived (Computed) Attributes
SQL Primer Derived (Computed) Attributes Queries can be used to compute derived attributes. select order_num, cust_num, sale_date, ship_date, total_invoice, amount_paid, total_invoice - amount_paid as balance_due from orders; Derived attributes are often computed as part of a view. create view extended_orders as ©SoftMoore Consulting
29
SQL Primer SQL Updates ©SoftMoore Consulting
30
Update Statements INSERT INTO – inserts rows
SQL Primer Update Statements INSERT INTO – inserts rows DELETE FROM – deletes rows UPDATE – modifies attribute values ©SoftMoore Consulting
31
Adding Rows to a Table -- insert a single row, all columns
SQL Primer Adding Rows to a Table -- insert a single row, all columns insert into customer values (6159, 'George W. Bush', '1600 Pennsylvania Avenue', 'Washington', 'DC', '20000', ' ') -- insert a single row, selected columns -- (uses defaults/nulls) insert into customer (cust_num, name, phone) values (8152, 'John Smith', ' ') -- insert multiple rows with a query select cust_num, name, phone from customer_temp; where state = 'SC'; ©SoftMoore Consulting
32
Deleting Rows from a Table
SQL Primer Deleting Rows from a Table General form delete from table where condition; Example delete from vendor where vendor_num in (2190, 5001, 5002); Note: If you omit the “where” clause, you will delete all rows in the table! ©SoftMoore Consulting
33
Modifying Data in a Table
SQL Primer Modifying Data in a Table General form update table set name1 = value1, name2 = value2, ... where condition; Example -- give everyone in IT a 6% raise update employee set salary = salary*1.06 where dept = 'IT'; ©SoftMoore Consulting
34
Modifying Data Using Views
SQL Primer Modifying Data Using Views Update statements can also be used to modify data through updateable views. Conditions for an updateable view one table subset of columns and rows no summarizing or condensing ©SoftMoore Consulting
35
SQL Primer SQL Data Definition ©SoftMoore Consulting
36
Data Definition in SQL CREATE DROP ALTER (restructure) schema – domain
SQL Primer Data Definition in SQL CREATE schema – domain table – view index DROP ALTER (restructure) ©SoftMoore Consulting
37
Creating a Table: Example 1
SQL Primer Creating a Table: Example 1 create table customer ( cust_num integer not null, last_name varchar(25) not null, first_name varchar(20), company_name varchar(40), _addr varchar(40) not null, constraint customer_pk primary key (cust_num), constraint customer_ak unique( _addr) ); ©SoftMoore Consulting
38
Creating a Table: Example 2
SQL Primer Creating a Table: Example 2 create table orders ( order_num integer not null, cust_num integer, sale_date date not null, ship_date date, total_invoice decimal(10,2), amount_paid decimal(10,2), constraint orders_pk primary key (order_num), constraint customer_fk foreign key (cust_num) references customer(cust_num) on delete cascade ); ©SoftMoore Consulting
39
Creating a Table from a Query
SQL Primer Creating a Table from a Query create table sales_personel as select employee_num, name, phone_num from employee where dept = 'SALES'; ©SoftMoore Consulting
40
Creating a View Views are created using queries
SQL Primer Creating a View Views are created using queries create view sales_personel as select employee_num, name, phone_num from employee where dept = 'SALES'; Access does not support views directly, but it allows stored queries which accomplish similar goals. ©SoftMoore Consulting
41
Creating Indexes and Domains
SQL Primer Creating Indexes and Domains Creating an index create index cust_name_index on customer.last_name; Note: Database systems usually generate “backing indexes” automatically for primary key, foreign key, and unique constraints. Creating a domain create domain ssn_type as char(9); Note: The ability to create user-defined types (domains) is not available in some database systems. ©SoftMoore Consulting
42
Dropping Database Objects
SQL Primer Dropping Database Objects drop table employee; drop view sales_personel; drop index cust_name_index; ©SoftMoore Consulting
43
Adding Constraints to a Table
SQL Primer Adding Constraints to a Table -- adding a primary key alter table departments add constraint pk_departments primary key(dept_num); -- adding a foreign key alter table employee add constraint fk_emp_dept foreign key (dept_num) references departments(dept_num) on delete set null on update cascade; ©SoftMoore Consulting
44
Adding and Dropping Columns
SQL Primer Adding and Dropping Columns Adding a column to a table alter table orders add payment_method char(10); Note: Access requires “ADD COLUMN”, but the keyword “COLUMN” can usually be omitted for other database systems. Dropping a column from a table (not available in all database systems) drop column payment_method; To drop a foreign key column, the foreign key constraint must be dropped first. ©SoftMoore Consulting
45
SQL Primer The Data Dictionary Oracle has a Data Dictionary that maintains all information about the structure of the database (metadata) The Data Dictionary is itself a set of tables. USER_TABLES – ALL_TABLES USER_VIEWS – ALL_VIEWS USER_TAB_COLUMNS – ALL_TAB_COLUMNS Access does not provide a way to query the data dictionary but provides similar information through a GUI. ©SoftMoore Consulting
46
Obtaining Metadata (Oracle Only)
SQL Primer Obtaining Metadata (Oracle Only) -- find the names of all of your tables select table_name from user_tables; -- find information about columns select column_name, data_type, data_length from user_tab_columns where table_name = 'CUSTOMER'; -- find all constraints (e.g., keys) on the ORDERS table select * from user_cons_columns where table_name = 'ORDERS'; Note: Similar capabilities exist in other database systems. Example (Derby): select tablename from sys.systables; ©SoftMoore Consulting
47
Additional SQL Statements and Operators
SQL Primer Additional SQL Statements and Operators ©SoftMoore Consulting
48
Row Functions and Operators
SQL Primer Row Functions and Operators Row functions and operators can be used to calculate new values as part of a query select cust_num, name, phone from customer where credit_limit > 20000; ©SoftMoore Consulting
49
Sample Row Functions and Operators
SQL Primer Sample Row Functions and Operators Numeric * / SQRT (SQR) ABS FLOOR (INT) Text || (&) SUBSTR (MID) UPPER (UCASE) LENGTH (LEN) INITCAP (STRCONV(x, 3)) Date + number - (DATEDIFF) MONTHS_BETWEEN (DATEDIFF) Note: Values in parentheses are those for Access. ©SoftMoore Consulting
50
Example Using Row Functions
SQL Primer Example Using Row Functions -- find all employees who have been with the -- company at least one year select name, hire_date from employee where trunc(months_between(hire_date, sysdate), 0) > 12; ©SoftMoore Consulting
51
Column Functions Column functions can be used to summarize data
SQL Primer Column Functions Column functions can be used to summarize data Sample column functions MIN MAX COUNT SUM AVG Examples select count(*) from orders; select name from customer c, orders o where c.cust_num = o.cust_num and o.total_invoice in (select max(o.total_invoice) from orders); ©SoftMoore Consulting
52
Counting Distinct Values
By default, the count function does not eliminate duplicate values. In order to count the number of distinct values, combine the distinct keyword with the count function. Example select count(distinct state) as num_states from customer; ©SoftMoore Consulting
53
SQL Primer The GROUP BY Clause A GROUP BY clause can be used to group query results select state, count(state) from customer group by state order by state; A GROUP BY clause can use more than one column. When using the GROUP BY clause, only the column or columns in the GROUP BY expression and the built-in functions can be used in the expressions in the SELECT clause. ©SoftMoore Consulting
54
Using Summary Operators with a GROUP BY Clause
SQL Primer Using Summary Operators with a GROUP BY Clause Summary operators (AVG, MAX, SUM, etc.) can be applied to queries about groups of rows. The GROUP BY clause specifies the grouping attributes. select c.cust_num, c.name, avg(o.amount_paid) from customer c, orders o where c.cust_num = o.cust_num group by c.cust_num, c.name; As before we could simplify this query using the NATURAL JOIN operator. from customer c natural join orders o ©SoftMoore Consulting
55
SQL Primer The HAVING Clause When a query result contains data that is grouped and summarized, a HAVING clause can eliminate some of the groups. Example query without a HAVING clause (shows order count for all customers) select name, phone_num, count(order_num) from customer, orders where customer.cust_num=orders.cust_num group by name, phone_num order by name; ©SoftMoore Consulting
56
The HAVING Clause (continued)
SQL Primer The HAVING Clause (continued) Example query with a HAVING clause (shows order count for all customers with at least 3 orders) select name, phone_num, count(order_num) from customer, orders where customer.cust_num=orders.cust_num group by name, phone_num having count(order_num) >= 3 order by customer.name; Note: A “where” clause can’t be used with aggregate functions. ©SoftMoore Consulting
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.