An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo Nael Alian

Slides:



Advertisements
Similar presentations
Virtual training week 4 structured query language (SQL)
Advertisements

Database Systems: Design, Implementation, and Management Tenth Edition
Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
Murali Mani SQL DDL and Oracle utilities. Murali Mani Datatypes in SQL INT (or) INTEGER FLOAT (or) REAL DECIMAL (n, m) CHAR (n) VARCHAR (n) DATE, TIME.
SQL SQL stands for Structured Query Language SQL allows you to access a database SQL is an ANSI standard computer language SQL can execute queries against.
CS162 Discussion Notes March 31, 2011 Jorge Ortiz.
30-Jun-15 SQL A Brief Introduction. SQL SQL is Structured Query Language Some people pronounce SQL as “sequel” Other people insist that only “ess-cue-ell”
Introduction to Structured Query Language (SQL)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
1ISM - © 2010 Houman Younessi Lecture 3 Convener: Houman Younessi Information Systems Spring 2011.
Chapter 7: SQL, the Structured Query Language Soid Quintero & Ervi Bongso CS157B.
DATABASES AND SQL. Introduction Relation: Relation means table(data is arranged in rows and columns) Domain : A domain is a pool of values appearing in.
Copyright © Curt Hill SQL The Data Definition Language.
CPS120: Introduction to Computer Science Information Systems: Database Management Nell Dale John Lewis.
 SQL stands for Structured Query Language.  SQL lets you access and manipulate databases.  SQL is an ANSI (American National Standards Institute) standard.
Database A collection of related data. Database Applications Banking: all transactions Airlines: reservations, schedules Universities: registration, grades.
HAP 709 – Healthcare Databases SQL Data Manipulation Language (DML) Updated Fall, 2009.
IT – som værktøj Bent Thomsen Institut for Datalogi Aalborg Universitet.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Chapter 7 SQL HUANG XUEHUA. SQL SQL server2005 introduction Install components  management studio.
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
1 What is database 2? What is normalization? What is SQL? What is transaction?
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
Chapter 5: Part 1: DDL STRUCTURED QUERY LANGUAGE (SQL)
Using Special Operators (LIKE and IN)
1 Structured Query Language (SQL). 2 Contents SQL – I SQL – II SQL – III SQL – IV.
Nitin Singh/AAO RTI ALLAHABAD 1 SQL Nitin Singh/AAO RTI ALLAHABAD 2 OBJECTIVES §What is SQL? §Types of SQL commands and their function §Query §Index.
Information Technologies and Microsoft SQL Server Day 2 by Alper Özpınar
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 7 Introduction to Structured.
Topic 1: Introduction to SQL. SQL stands for Structured Query Language. SQL is a standard computer language for accessing and manipulating databases SQL.
SQL Unit – 2 Base Knowledge Presented By Mr. R.Aravindhan.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
1 DBS201: Introduction to Structure Query Language (SQL) Lecture 1.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
SQL. คำสั่ง SQL SQL stands for Structured Query Language is a standard language for accessing and manipulating databases.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Visual Programing SQL Overview Section 1.
SQL – Structured Query Language
SQL Jan 20,2014. DBMS Stores data as records, tables etc. Accepts data and stores that data for later use Uses query languages for searching, sorting,
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
ITS232 Introduction To Database Management Systems Siti Nurbaya Ismail Faculty of Computer Science & Mathematics, Universiti Teknologi MARA (UiTM), Kedah.
1 CS 430 Database Theory Winter 2005 Lecture 10: Introduction to SQL.
1 MySQL and SQL. 2 Topics  Introducing Relational Databases  Terminology  Managing Databases MySQL and SQL.
Distribution of Marks For Second Semester Internal Sessional Evaluation External Evaluation Assignment /Project QuizzesClass Attendance Mid-Term Test Total.
Introduction to Database SEM I, AY Department of Information Technology Salalah College of Technology Chapter No.3 SQL.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
MySQL Tutorial. Databases A database is a container that groups together a series of tables within a single structure Each database can contain 1 or more.
SQL Basics Review Reviewing what we’ve learned so far…….
Big Data Yuan Xue CS 292 Special topics on.
Fundamentals of DBMS Notes-1.
CHAPTER 7 DATABASE ACCESS THROUGH WEB
PL/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-1
STRUCTURED QUERY LANGUAGE
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Introduction To Structured Query Language (SQL)
Database systems Lecture 3 – SQL + CRUD
Introduction To Structured Query Language (SQL)
SQL (Structured Query Language)
Presentation transcript:

An Introduction to SQL Kirk Anne Computing & Information Technology SUNY Geneseo Nael Alian

What is a database?

Parts of a database Attributes (fields) – An attribute or field is a component of a record that describes something about an item. Records – A record is the representation of an individual item. Table – A collection of records Database – A collection of tables and rules for accessing the tables

Parts of a database Record Attribute/Field Tables Records become “rows” Attributes/fields become “columns” Rules determine the relationship between the tables and tie the data together to form a database

I need a new database! Many people ask for “new databases” when in fact they only need a new table within an existing database. The data within the tables should be all related somehow. – By owner – By project

Creating a database What information are we trying to store? How do we describe the information? Phone Book/Contact entries – Name – Address – Company – Phone Number – URL/Web Page – Age – Height (in meters) – Birthday – When we added the entry

Data Types Binary – Database specific binary objects – Pictures, digital signatures, etc. Boolean – True/False values Character – Fixed width or variable size Numeric – Integer, Real (floating decimal point), Money Temporal – Time, Date, Timestamp

Phone Book/Contact Record NameCharacter AddressCharacter CompanyCharacter Phone NumberCharacter URL/Web PageCharacter AgeInteger HeightReal (float) BirthdayDate When we added the entryTimestamp

All you need to know about SQL

What is SQL? 1. SQL stands for Structured Query Language 2. SQL lets you access and manipulate databases 3. SQL is an ANSI (American National Standards Institute) standard

SQL can execute queries against a database SQL can retrieve data from a database SQL can insert records in a database SQL can update records in a database SQL can delete records from a database SQL can create new databases SQL can create new tables in a database SQL can create stored procedures in a database SQL can create views in a database SQL can set permissions on tables, procedures, and views

SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition Language (DDL). The query and update commands form the DML 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

The DDL 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

Basic SQL Commands Creating tables with CREATE Adding data with INSERT Viewing data with SELECT Removing data with DELETE Modifying data with UPDATE Destroying tables with DROP

Creating tables with CREATE Generic form CREATE TABLE tablename ( column_name data_type attributes…, … ) Table and column names can’t have spaces or be “reserved words” like TABLE, CREATE, etc.

Phone Book/Contact Record NameCharacter AddressCharacter CompanyCharacter Phone NumberCharacter URL/Web PageCharacter AgeInteger HeightReal (float) BirthdayDate When we added the entryTimestamp

Phone Book/Contact Table CREATE TABLE contacts ( NameVARCHAR(40), Address VARCHAR(60), Company VARCHAR(60), Phone VARCHAR(11), URLVARCHAR(80), AgeINT, HeightFLOAT, BirthdayDATE, WhenEnteredTIMESTAMP ); Plan your tables very carefully! Once created, they are difficult to change!

Phone Book/Contact Table CREATE TABLE contacts ( ContactIDINT PRIMARY KEY, NameVARCHAR(40), Address VARCHAR(60), Company VARCHAR(60), Phone VARCHAR(11), URLVARCHAR(80), AgeINT, HeightFLOAT, BirthdayDATE, WhenEnteredTIMESTAMP ); If you are going to use the relational nature of a database, don’t forget you need to have a unique way to access records! There is a way to make the key automatically increment, so you don’t have to worry about which one is next.

Data Types Binary – Database specific binary objects (BLOB) Boolean – True/False values (BOOLEAN) Character – Fixed width (CHAR) or variable size (VARCHAR) Numeric – Integer (INT), Real (FLOAT), Money (MONEY) Temporal – Time (TIME), Date (DATE), Timestamp (TIMESTAMP)

Create Table emp ( eno Varchar2(10) Not Null, ename Varchar2(30),age Varchar2(5) Null, salary Number(10), birth_day Date ) ; انشاء جدول يحتوي على القيم التالية اسم الحقل نوعةطولة يجب ادخال القيمة enoVarchar210not Null يجب ادخالها enameVarchar230not Null يجب ادخالها ageVarchar25 لايجب ادخالها salarynumber10 Null لايجب ادخالها birth_daydate- لايجب ادخالها

Adding data with INSERT Generic Form INSERT INTO tablename (column_name,…) VALUES (value,…)

Inserting a record into ‘contacts’ INSERT INTO contacts (contactid,name,address,company,phone,url,a ge,height,birthday,whenentered) VALUES (1,‘Joe’,’123 Any St.’,’ABC’, ’ ’,‘ ’6/14/1972’, now());

Inserting a partial record INSERT INTO contacts (contactid,name,phone) VALUES (2,’Jane’,’ ’);

Automatic key generation CREATE SEQUENCE contactidseq; Change the ContactID line in the CREATE TABLE to: ContactIDINT DEFAULT nextval(‘contactidseq’) PRIMARY KEY Or when inserting into a table INSERT contacts (contactid,name,phone) VALUES (nextval(‘contactidseq’),’Jack’, ‘ ’);

Insert Into emp (eno,ename) values ('10', 'صالح' ) اضافة البيانات التالية الى الحقول المحددة Insert Into emp (eno,ename) values (&no, '&name' ); اضافة البيانات التالية الى الحقول المحددة ويطلب القيم عند التنفيذ

Viewing data with SELECT Generic Form SELECT column,… FROM table,… WHERE condition GROUP BY group_by_expression HAVING condition ORDER BY order_expression The most used command Probably the most complicated also If used improperly, can cause very long waits because complex computations

A few simple SELECTs SELECT * FROM contacts; – Display all records in the ‘contacts’ table SELECT contactid,name FROM contacts; – Display only the record number and names SELECT DISTINCT url FROM contacts; – Display only one entry for every value of URL.

Select Distinct ename from emp ; عرض اسماء الموظفين بدون تكرار Select Distinct ename,eno from emp ; عرض اسماء الموظفين وارقامهم دون تكرار قيم حقل الاسم

Refining selections with WHERE The WHERE “subclause” allows you to select records based on a condition. SELECT * FROM contacts WHERE age<10; – Display records from contacts where age<10 SELECT * FROM contacts WHERE age BETWEEN 18 AND 35; – Display records where age is 18-35

Additional selections The “LIKE” condition – Allows you to look at strings that are alike SELECT * FROM contacts WHERE name LIKE ‘J%’; – Display records where the name starts with ‘J’ SELECT * FROM contacts WHERE url LIKE ‘%.com’; – Display records where url ends in “.com”

Select * from emp ; Emp عرض جميع بيانات الجدول Select ename from emp ; عرض اسماء الموظفين من جدول الموظفين Select salary*0.91 from emp ; عرض رواتب الموظفين مخصوم منها التقاعد 9 في المائة

Removing data with DELETE Generic Form DELETE FROM table WHERE condition; DELETE FROM contacts WHERE age<13;

Delete * from emp where eno=12 ; حذف جميع بيانات الموظف الذي رقمة 12 Delete * from emp where eno=12 ; حذف جميع بيانات الموظف الذي رقمة 12 Delete eno,name from emp where eno=12 ; حذف رقم واسم الموظف الذي رقمة 12

Modifying data with UPDATE Generic Form UPDATE table SET column=expression WHERE condition; UPDATE contacts SET company=‘AOL’ WHERE company=‘Time Warner’;

Destroying tables with DROP Generic Form DROP TABLE tablename; DROP TABLE contacts;

More about SELECT

Different types of JOINs “Inner Join” – Unmatched rows in either table aren’t printed “Left Outer Join” – All records from the “left” side are printed “Right Outer Join” – All records from the “right” side are printed “Full Outer Join” – All records are printed Multiple Table Join – Join records from multiple tables

General form of SELECT/JOIN SELECT columns,… FROM left_table join_type JOIN right_table ON condition; SELECT name,phone FROM people JOIN phonenumbers ON people.id=phonenumbers.id;

Other versions SELECT name,phone FROM people LEFT JOIN phonenumbers ON people.id=phonenumbers.id; SELECT name,phone FROM people RIGHT JOIN phonenumbers ON people.id=phonenumbers.id; SELECT name,phone FROM people FULL JOIN phonenumbers ON people.id=phonenumbers.id;

“Theta style” vs. ANSI Theta Style (used in most SQL books) SELECT name,phone,zip FROM people, phonenumbers, address WHERE people.addressid=address.addressid AND people.id=phonenumbers.id; ANSI Style uses JOIN SELECT name,phone,zip FROM people JOIN phonenumbers ON people.id=phonenumbers.id JOIN address ON people.addressid=address.addressid;

Other SELECT examples SELECT * FROM contacts WHERE name is NULL; SELECT * FROM contacts WHERE zip IN (‘14454’,’12345’); SELECT * FROM contacts WHERE zip IN ( SELECT zip FROM address WHERE state=‘NY’ );

GROUP BY/HAVING The “GROUP BY” clause allows you to group results together with “aggregate functions” – AVG(), COUNT(), MAX(), MIN(), SUM() – COUNT DISTINCT HAVING allows you to search the GROUP BY results

GROUP BY Examples SELECT company,count(company) FROM contacts GROUP BY company; SELECT company,count(company) FROM contacts GROUP BY company HAVING count(company) > 5;

ORDER BY The “ORDER BY” clause allows you to sort the results returned by SELECT. SELECT * FROM contacts ORDER BY company; SELECT * FROM contacts ORDER BY company, name;

Views You can use “CREATE VIEW” to create a virtual table from a SELECT statement. CREATE VIEW contactview AS (SELECT name,phone,zip FROM people,phonenumbers,address WHERE people.id=phonenumbers.id AND people.addressid=address.addressid);