SQL Short introduction 1
Overview SQL, which stands for Structured Query Language, is used to communicate with a database. Through SQL one can create, manipulate, query and delete tables and contents. data 1 data 2 data 3 data 4 Customer Cust_id FirstName LastName 01 02 03 04 Mickey Donald Pin Tove Mouse Duck Nokio Svens A database consists of one or more tables. A table is identified by its name. A table is made up of : Columns, which contain the column name and data type And Rows, which contain the records or data for the columns. Each record has a unique identifier or primary key. 2 2
What can SQL do? Execute queries against a database Retrieve data from a database Insert records in a database Update records in a database Delete records from a database Create new databases Create new tables in a database Create stored procedures in a database Create views in a database Set permissions on tables, procedures, and views 3 http://www.w3schools.com/sql/sql_intro.asp 3
DML & DDL SQL can be divided into two parts: The Data Manipulation Language (DML) Is the query and update commands part of SQL: SELECT - extracts data from a database UPDATE - updates data in a database DELETE - deletes data from a database INSERT INTO - inserts new data into a database Data Definition Language (DDL) This part of SQL permits database tables to be created or deleted. It also define indexes (keys), specify links between tables, and impose constraints between tables. The most important DDL statements in SQL are: CREATE DATABASE - creates a new database ALTER DATABASE - modifies a database CREATE TABLE - creates a new table ALTER TABLE - modifies a table DROP TABLE - deletes a table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index 4 http://www.w3schools.com/sql/sql_syntax.asp http://onlamp.com/pub/a/onlamp/2001/09/13/aboutsql.html RDBMS : Relational DataBase Management System http://troels.arvin.dk/db/rdbms/ 4
Data type The table outlines some of the common names of data types between the various database platforms Access SQL-Server Oracle MySQL PostgreS QL boolean Yes/No Bit Byte N/A Boolean integer Number (integer) Int Number Int Integer (synonyms) Integer Int float Number (single) Float Real Number Float Numeric currency Currency Money N/A N/A Money string (fixed) N/A Char Char Char Char string (variable) Text (<256) Memo (65k+) Varchar Varchar Varchar2 Varchar Varchar binary object OLE Object Memo Binary (fixed up to 8K) Varbinary (<8K) Image (<2GB) Long Raw Blob Text Binary Varbinary 5 http://www.techonthenet.com/sql/datatypes.php 5
Zero is not NULL NULL values are 'nothing' values. When a value is null, it means the value is empty and contains no value -- not even '0'. NULLs are unique data types that are usually the default setting for all table columns. When a SQL developer runs across a NULL value in a database, it is generally an indication that this value is either new or has not been modified. 6 http://en.wikipedia.org/wiki/null_(sql) 6
SQL Statements Most of the actions you need to perform on a database are done with SQL statements. data 1 Customer Cust_id FirstName LastName 01 Mickey Mouse In the following slides we will see SQL statements that acts on the the records at the customer table data 2 data 3 data 4 02 03 04 Donald Pin Tove Duck Nokio Svens 7 7
Create 8
CREATE TABLE Statement The CREATE TABLE statement is used to create a table in a database. CREATE TABLE table_name ( column_name1 data_type [primary key], column_name2 data_type, column_name3 data_type,... [,primary key] ); Note: MySQL and Oracle have different ways to define Primary Key CREATE TABLE Cars ( P_Id int PRIMARY KEY, Brand varchar(50), Color varchar(10) ) ; P_Id Brand Cars Color 9 9
Select 10
SELECT statement The SELECT statement is used to select data from a database. The result is stored in a result table, called the result-set. SELECT [DISTINCT] column_name(s) FROM table_name WHERE column_name (operator) value [AND/OR]... ; In a table, some of the columns may contain duplicate values. sometimes you will want to list only the different (distinct) values in a table. data 1 data 2 Cust_id 01 02 Customer FirstName LastName Mickey Mouse Donald Duck ex: SELECT * FROM customer WHERE FirstName='Tove' AND LastName='Svens ; data 3 data 4 03 04 Pin Tove Nokio Svens 11 11
Operators Allowed in the WHERE Clause Operators Allowed in the WHERE Clause With the WHERE clause, the following operators can be used: Operator = <> > < >= <= BETWEEN LIKE IN Equal Not equal Greater than Less than Greater than or equal Less than or equal Between an inclusive range Search for a pattern Description If you know the exact value you want to return for at least one of the columns Note: In some versions of SQL the <> operator may be written as!= 12 12
Matematical operations SQL matematical operations are done with operators (+, -, *, /, %). We can use SQL like a calculator. ex: SELECT (price*quantity), round(price) FROM items_ordered GROUP BY items ; 13 http://www.tizag.com/sqltutorial/sqloperators.php 13
Aggregate functions Aggregate Functions (aggregate or summation function) is used to calculate a "column of numerical data" from the SELECT statement. They are summarized in substantially the result of a particular column of the selected data Example, you may want to know which row in the table that has the maximum or minimum value. ex: SELECT item, SUM(price), MAX(price), Min(price) FROM items_ordered GROUP BY item ; 14 http://iwtjanster.idg.se/webbstudio/pub/artikel.asp?id=73 http://oreilly.com/catalog/sqlnut/chapter/ch04.html 14
The ORDER BY Keyword The ORDER BY keyword is used to sort the result-set by a specified column and sort the records in ascending order by default. If you want to sort the records in a descending order, you can use the DESC keyword. SELECT column_name(s) FROM table_name ORDER BY column_name(s) [ASC DESC] ; Cust_id Customer FirstName LastName data 2 02 Donald Duck data 1 01 Mickey Mouse ex: SELECT * FROM customer ORDER BY LastName; data 3 03 Pin Nokio data 4 04 Tove Svens 15 15
View 16
CREATE VIEW statement A view is a virtual table. In SQL, a view is a virtual table based on the resultset of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table. Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL statement, every time a user queries a view. CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition; 17 http://www.w3schools.com/sql/sql_view.asp 17
myownview We can have a view that always show who has ordered what: CREATE VIEW myownview AS SELECT Customers.FirstName, Customers.LastName, Products.Name FROM Customers, Products, Orders WHERE Customers.Cust_ID = Orders.Cust_ID AND Products.Part_No = Orders.Part_No 18 18
Update 19
UPDATE Statement The UPDATE statement is used to update existing records in a table. UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value; Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated! Customer Cust_id FirstName LastName data 2 02 Donald Duck data 1 01 Mickey Mouse ex: UPDATE customer SET LastName='Nissen 67' WHERE FirstName= Tove' ; data 3 data 4 03 04 Pin Tove Nokio Nissen Svens67 data 5 05 Nilsen Bakken 2 20 20
Delete 21
DELETE Statement The DELETE statement is used to delete rows in a table. DELETE [*] FROM table_name WHERE some_column=some_value Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted! data 2 data 1 Customer Cust_id FirstName LastName 02 01 Donald Mickey Duck Mouse data 3 03 Pin Nokio ex: DELETE FROM customer WHERE FirstName='Tove' data 4 04 Tove Nissen 67 data 5 05 Nilsen Bakken 2 22 22
Alter 23
ALTER TABLE statement The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. To add a column in a table, use the following syntax: ALTER TABLE table_name ADD column_name datatype; To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column): ALTER TABLE table_name DROP COLUMN column_name; To change the data type of a column in a table, use the following syntax: ALTER TABLE table_name ALTER COLUMN column_name datatype; 24 24
Not often used in test ALTER TABLE statement Customer Cust_id FirstName LastName Address data 2 02 Donald Duck data 1 01 Mickey Mouse data 3 03 Pin Nokio ex: ALTER customer ADD Address varchar(150) data 4 04 Tove Nissen 67 data 5 05 Nilsen Bakken 2 25 25
Insert into 26
INSERT INTO Statement The INSERT INTO statement is used to insert a new row in a table. It is possible to write the INSERT INTO statement in two forms: The first form doesn't specify the column names where the data will be inserted, only their values: INSERT INTO table_name VALUES (value1, value2, value3,...); Customer Cust_id FirstName LastName The second form specifies both the column names and the values to be inserted: INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,...); data 2 data 1 data 3 02 01 03 Donald Mickey Pin Duck Mouse Nokio ex: INSERT INTO customer VALUES (05,'Nilsen', 'Bakken 2'); data 4 04 Tove Svens data 5 05 Nilsen Bakken 2 27 27
Drop 28
DROP Statement The DROP TABLE statement is used to delete a table. DROP TABLE table_name The DROP DATABASE statement is used to delete a database. DROP DATABASE database_name What if we only want to delete the data inside the table, and not the table itself? Then, use the TRUNCATE TABLE statement: TRUNCATE TABLE table_name 29 http://www.w3schools.com/sql/sql_drop.asp 29
Join 30
JOIN keyword The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables. Tables in a database are often related to each other with keys. A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table. 31 31
JOIN keyword We can obtain information on who has ordered what: SELECT Customers.FirstName, Customers.LastName, Products.Name FROM Customers, Products, Orders WHERE Customers.Cust_ID = Orders.Cust_ID AND Products.Part_No = Orders.Part_No 32 32
Different SQL JOINs INNER JOIN: Return rows when there is at least one match in both tables LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table [FULL] JOIN: Return rows when there is a match in one of the tables SELECT Customers.FirstName, Customers.LastName, Orders.Date FROM Customers INNER JOIN Orders ON Customers.Cust_ID = Orders.Cust_ID 33 33
Hand s on 34
SQL Try It http://www.w3schools.com/sql/sql_tryit.asp 35 35
SQL Quiz http://www.w3schools.com/quiztest/quiztest.asp?qtest=sql 36 36
Oracle SQL Developer 37
Oracle SQL Developer http://www.oracle.com/technology/products/database/sql_developer/index.html 38 38
39 39
40 40
Oracle SQL - Data Modeler 41 41