SQL. Short introduction



Similar documents
Learning MySQL! Angola Africa SELECT name, gdp/population FROM world WHERE area > !

P_Id LastName FirstName Address City 1 Kumari Mounitha VPura Bangalore 2 Kumar Pranav Yelhanka Bangalore 3 Gubbi Sharan Hebbal Tumkur

How To Create A Table In Sql (Ahem)

A table is a collection of related data entries and it consists of columns and rows.

Database Query 1: SQL Basics

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

Introduction to Microsoft Jet SQL

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

3.GETTING STARTED WITH ORACLE8i

A Brief Introduction to MySQL

A basic create statement for a simple student table would look like the following.

Structured Query Language. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics

Information Systems SQL. Nikolaj Popov

Financial Data Access with SQL, Excel & VBA

History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG)

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Relational Database: Additional Operations on Relations; SQL

Information Technology NVEQ Level 2 Class X IT207-NQ2012-Database Development (Basic) Student s Handbook

Database Migration from MySQL to RDM Server

Oracle SQL. Course Summary. Duration. Objectives

B.1 Database Design and Definition

Database Administration with MySQL

Oracle Database: SQL and PL/SQL Fundamentals

A Comparison of Database Query Languages: SQL, SPARQL, CQL, DMX

Using AND in a Query: Step 1: Open Query Design

Databases in Engineering / Lab-1 (MS-Access/SQL)

Oracle Database 10g Express

Oracle Database: SQL and PL/SQL Fundamentals NEW

SQL 2: GETTING INFORMATION INTO A DATABASE. MIS2502 Data Analytics

MYSQL DATABASE ACCESS WITH PHP

Using Multiple Operations. Implementing Table Operations Using Structured Query Language (SQL)

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database 10g: Introduction to SQL

SQL Server An Overview

6 CHAPTER. Relational Database Management Systems and SQL Chapter Objectives In this chapter you will learn the following:

IT2305 Database Systems I (Compulsory)

Using SQL Server Management Studio

Using the SQL Procedure

Introduction to SQL and database objects

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

MS ACCESS DATABASE DATA TYPES

4. The Third Stage In Designing A Database Is When We Analyze Our Tables More Closely And Create A Between Tables

SQL: joins. Practices. Recap: the SQL Select Command. Recap: Tables for Plug-in Cars

Copyr i g ht 2012, SAS Ins titut e Inc. All rights res er ve d. DATA MANAGEMENT FOR ANALYTICS

Introduction to Database. Systems HANS- PETTER HALVORSEN,

SQL Basics for RPG Developers

Services. Relational. Databases & JDBC. Today. Relational. Databases SQL JDBC. Next Time. Services. Relational. Databases & JDBC. Today.

David M. Kroenke and David J. Auer Database Processing: Fundamentals, Design and Implementation

Teach Yourself InterBase

Information and Computer Science Department ICS 324 Database Systems Lab#11 SQL-Basic Query

SQL Server Database Coding Standards and Guidelines

MS Access Lab 2. Topic: Tables

CSC 443 Data Base Management Systems. Basic SQL

Oracle 10g PL/SQL Training

5. CHANGING STRUCTURE AND DATA

Mul$media im Netz (Online Mul$media) Wintersemester 2014/15. Übung 03 (Nebenfach)

CSI 2132 Lab 3. Outline 09/02/2012. More on SQL. Destroying and Altering Relations. Exercise: DROP TABLE ALTER TABLE SELECT

Information Systems Modelling Information Systems I: Databases

Database: SQL, MySQL

Relational Databases. Christopher Simpkins

Structured Query Language (SQL)

IT2304: Database Systems 1 (DBS 1)

Programming with SQL

Apache Cassandra Query Language (CQL)

Advance DBMS. Structured Query Language (SQL)

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries

Extracting META information from Interbase/Firebird SQL (INFORMATION_SCHEMA)

Introducción a las bases de datos SQL Libro de referencia

Oracle Database 12c: Introduction to SQL Ed 1.1

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

Oracle Database: Introduction to SQL

4 Logical Design : RDM Schema Definition with SQL / DDL

Oracle Database: Introduction to SQL

Conventional Files versus the Database. Files versus Database. Pros and Cons of Conventional Files. Pros and Cons of Databases. Fields (continued)

A brief MySQL tutorial. CSE 134A: Web Service Design and Programming Fall /28/2001

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Introduction to SQL for Data Scientists

Managing Objects with Data Dictionary Views. Copyright 2006, Oracle. All rights reserved.

Oracle Database 11g SQL


Microsoft Access 3: Understanding and Creating Queries

SQL Injection. The ability to inject SQL commands into the database engine through an existing application

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

Chapter 6: Physical Database Design and Performance. Database Development Process. Physical Design Process. Physical Database Design

FileMaker 13. SQL Reference

Introduction to SQL and SQL in R. LISA Short Courses Xinran Hu

Deleting A Record Updating the Database Binding Data Tables to Controls Binding the Data Table to the Data Grid View...

Database Design and Implementation

Creating Database Tables in Microsoft SQL Server

BCA. Database Management System

Examine the structure of the EMPLOYEES table: EMPLOYEE_ID NUMBER Primary Key FIRST_NAME VARCHAR2(25) LAST_NAME VARCHAR2(25)

New SQL Features in Firebird 3

Access Queries (Office 2003)

Databases 2011 The Relational Model and SQL

Transcription:

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