MIT1 264JF13 Lect 11 SQL
MIT1 264JF13 Lect 11 SQL
264 Lecture 11
2
SQL
• Structured query language (SQL) used for
– Data definition (DDL): tables and views (virtual tables). These
are the basic operations to convert a data model to a database
– Data manipulation (DML): user or program can INSERT,
DELETE, UPDATE or retrieve (SELECT) data.
– Data integrity: referential integrity and transactions. Enforces
keys (primary and foreign)
– Access control: security
– Data sharing: by concurrent users
• Not a complete language like Java, Visual Basic or C++
– SQL is sub-language of about 30 statements
– Embedded in another language or tool for database access
– SQL has several inconsistencies; NULLs are problematic
– Portable across operating systems and somewhat among
vendors
– Declarative language, not procedural
3
Things that vary among SQL implementations
• Error codes
• Data types supported (dates/times, currency,
string/text variations)
• System tables, about the structure of the database
itself
• Interactive SQL
• Programming interface: no vendor follows the
standard
• Dynamic SQL, used for report writers and query
tools
• Implementer-defined variations within the standard
• Database initialization, opening and connection
• Whether case matters (upper, lower case)
4
SQL SELECT
5
Example tables
OrderNbr Cust Prod Qty Amt Disc
Orders 1 211 Bulldozer 7 $31,000.00 0.2
2 522 Riveter 2 $4,000.00 0.3
3 522 Crane 1 $500,000.00 0.4
7
Using SQL Server and Management Studio
9
Exercise 2 SQL queries: insert, delete, update
• Find the average sale
– SELECT AVG(Amt) FROM Orders;
• Find the average sale for a customer
– SELECT AVG(Amt) FROM Orders WHERE Cust = 211;
• Add an office
– INSERT INTO Offices (OfficeNbr, City, State, Region, Target,
Sales, Phone) VALUES (‘55’, ‘Dallas’,‘TX’,‘West’, 200000, 0,
‘214.333.2222’);
• Delete a customer
– DELETE FROM Customers WHERE Company = ‘Connor Co’;
– (Syntax is valid but command will fail due to referential
integrity)
• Exercise: Create (insert) a new order and delete it
– Omit OrderNbr in INSERT because it’s auto-generated
• Raise a credit limit
– UPDATE Customers
SET CreditLimit = 75000 WHERE Company = ‘Amaratunga 10
Exercise 3: SELECT * and duplicates
11
MIT OpenCourseWare
http://ocw.mit.edu
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.