Introduction to Databases and SQL

Similar documents
Using PHP with MYSQL

Instructor: Craig Duckett. Lecture 03: Tuesday, April 3, 2018 SQL Sorting, Aggregates and Joining Tables

CS 327E Lecture 2. Shirley Cohen. January 27, 2016

Consistency The DBMS must ensure the database will always be in a consistent state. Whenever data is modified, the database will change from one

SQL Commands & Mongo DB New Syllabus

Chapter 13 : Informatics Practices. Class XI ( As per CBSE Board) SQL Commands. New Syllabus Visit : python.mykvs.in for regular updates

Ruby on Rails Welcome. Using the exercise files

SQL Data Definition Language: Create and Change the Database Ray Lockwood

Oracle Database 10g Express

The Stack, Free Store, and Global Namespace

Instructor: Craig Duckett. Lecture 04: Thursday, April 5, Relationships

SQL - Tables. SQL - Create a SQL Table. SQL Create Table Query:

SQL (and MySQL) Useful things I have learnt, borrowed and stolen

An Introduction to Stored Procedures in MySQL 5 by Federico Leven6 Apr 2011

T-sql Grant View Definition Example

Relational databases and SQL

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology.

CGS 3066: Spring 2017 SQL Reference

OKC MySQL Users Group

Formal Methods of Software Design, Eric Hehner, segment 24 page 1 out of 5

Instructor: Craig Duckett. Lecture 07: Tuesday, April 17 th, 2018 Conflicts and Isolation, MySQL Workbench

Using X-Particles with Team Render

WHAT IS A DATABASE? There are at least six commonly known database types: flat, hierarchical, network, relational, dimensional, and object.

Introduction to Databases. MySQL Syntax Guide: Day 1

Lesson 3 Transcript: Part 1 of 2 - Tools & Scripting

Ten Great Reasons to Learn SAS Software's SQL Procedure

Advance Database Systems. Joining Concepts in Advanced SQL Lecture# 4

MySQL Workshop. Scott D. Anderson

Chapter 2. DB2 concepts

The Entity-Relationship Model (ER Model) - Part 2

Introduction to SQL on GRAHAM ED ARMSTRONG SHARCNET AUGUST 2018

SQL stands for Structured Query Language. SQL is the lingua franca

VS2010 C# Programming - DB intro 1

Learning Objectives. Description. Your AU Expert(s) Trent Earley Behlen Mfg. Co. Shane Wemhoff Behlen Mfg. Co.

EE221 Databases Practicals Manual

Get Table Schema In Sql Server 2008 To Add Column If Not Exists >>>CLICK HERE<<<

DATABASES SQL INFOTEK SOLUTIONS TEAM

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

COMP283-Lecture 6 Applied Database Management

The Institute of Computer Accountants 27, N. S. Road, 4th & 5th Floor, Kolkata Windows 10 Updates

Assignment 1 DUE TONIGHT

CSCI 1100L: Topics in Computing Lab Lab 07: Microsoft Access (Databases) Part I: Movie review database.

how its done in about the five most common SQL implementations.

INTERMEDIATE SQL GOING BEYOND THE SELECT. Created by Brian Duffey

Lecture 5. Monday, September 15, 2014

GlobAl EDITION. Database Concepts SEVENTH EDITION. David M. Kroenke David J. Auer

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

What is SQL? Toolkit for this guide. Learning SQL Using phpmyadmin

PHP6 AND MYSQL BIBLE BY STEVE SUEHRING, TIM CONVERSE, JOYCE PARK

Introduction to Databases

Mysql Create Table Example Primary Key Foreign

Server Side Scripting Report

Chapter 8: Working With Databases & Tables

MITOCW MIT6_172_F10_lec18_300k-mp4

A Primer in Web Application Development

Instructor: Craig Duckett. Lecture 14: Tuesday, May 15 th, 2018 Stored Procedures (SQL Server) and MySQL

Today Learning outcomes LO2

Oracle Exam 1z0-882 Oracle Certified Professional, MySQL 5.6 Developer Version: 7.0 [ Total Questions: 100 ]

Preventing system crashes with Resource Meter

Database and MySQL Temasek Polytechnic

A practical introduction to database design

Hi everyone. I hope everyone had a good Fourth of July. Today we're going to be covering graph search. Now, whenever we bring up graph algorithms, we

AN INTRODUCTION TO WEB PROGRAMMING. Dr. Hossein Hakimzadeh Department of Computer and Information Sciences Indiana University South Bend, IN

TestComplete 3.0 Overview for Non-developers

Release Notes. Installing. Upgrading. Registration Keys

CHAPTER 11. Data Normalization

PHP & MySQL For Dummies, 4th Edition PDF

MySQL. A practical introduction to database design

COPYRIGHTED MATERIAL. Databases

tablename ORDER BY column ASC tablename ORDER BY column DESC sortingorder, } The WHERE and ORDER BY clauses can be combined in one

The following content is provided under a Creative Commons license. Your support

MySQL 5.0 Stored Procedures, VIEWs and Triggers MySQL UC 2005, Santa Clara

BEGINNER PHP Table of Contents

Where Are We? Next Few Lectures. Integrity Constraints Motivation. Constraints in E/R Diagrams. Keys in E/R Diagrams

It Might Be Valid, But It's Still Wrong Paul Maskens and Andy Kramek

This lab will introduce you to MySQL. Begin by logging into the class web server via SSH Secure Shell Client

Manual Triggers Sql Server 2008 Examples

Managing Your Database Using Oracle SQL Developer

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

Vive La Difference How SQLite varies from VFP SQL

Basic Reports & Dashboards

CS103 Spring 2018 Mathematical Vocabulary

Manage Music Iphone 5

I'm Andy Glover and this is the Java Technical Series of. the developerworks podcasts. My guest is Brian Jakovich. He is the

Assignment 7: Integrity Constraints

CIS 45, The Introduction. What is a database? What is data? What is information?

Data Management Lecture Outline 2 Part 2. Instructor: Trevor Nadeau

CPS221 Lecture: Relational Database Querying and Updating

T-sql Check If Index Exists Information_schema

Printing Table of Contents. Printing Overview

CS Reading Packet: "Views, and Simple Reports - Part 1"

CPS221 Lecture: Relational Database Querying and Updating

Keys are fields in a table which participate in below activities in RDBMS systems:

AS COMPUTERS AND THEIR USER INTERFACES have become easier to use,

CIS Reading Packet: "Views, and Simple Reports - Part 1"

Database: Introduction

Skill 1: Multiplying Polynomials

Unit 27 Web Server Scripting Extended Diploma in ICT

Lecture 8. Monday, September 29, 2014

STORED PROCEDURE AND TRIGGERS

Transcription:

Introduction to Databases and SQL

Files vs Databases In the last chapter you learned how your PHP scripts can use external files to store and retrieve data. Although files do a great job in many circumstances, they're pretty inflexible as data storage solution. For example, if you need to filter or sort the data retrieved from a file, you have to write your own PHP code to do it. Not only is this tiresome, but if you're working with large sets of data for example, hundreds of thousands of user records your script will probably grind to a halt. Not good if you're hoping to build a popular Web site.

Databases Often, the most efficient alternative to text files is to use a database engine commonly known as a Database Management System (DBMS) to store, retrieve, and modify the data for you. A good database engine serves as a smart tool between you and your data, organizing and cataloging the data for quick and easy retrieval. You can use any database systems in your PHP applications. In this course, you'll focus on just one database engine: MySQL. Also, the database model dictates how the data is stored and accessed. Many different database models are used today but here, we will focus on relational model, which is the model MYSQL uses.

Relational Databases In simple terms, a relational database is any database system that allows data to be associated and grouped by common attributes. For example, a bunch of payroll records might be grouped by employee, by department, or by date. Typically, a relational database arranges data into tables, where each table is divided into rows and columns of data. In database language, each row in a table represents a data record : a set of connected pieces of data, such as information relating to a particular person. Likewise, each column represents a field : a specific type of data that has the same significance for each record in the table, such as first name or age.

Relational Database Example Here's an example of a database table. Suppose that the manager of a football team sets up a database so that she can track the matches in which her players compete. She asks each player to enter his details into the database after each match. After two matches the manager's table, called matchlog, looks like this:

The Example In this table, you can see that each row represents a particular set of information about a player who played on a certain date, and each column contains a specific type of data for each person or date. Notice that each column has a name at the top of the table to identify it; this is known as the field name or column name

Normalization The manager soon realizes that this matchlog table is going to be huge after everyone on the team has played an entire season's worth of games. As you can see, the structure of the table is inefficient because each player's details (number, name, phone number, and so on) are entered every time he plays a match. Such redundancy is undesirable in a database. For example, say that the player with the number 6 keeps dropping the ball, and his teammates decide to give him a new nickname (which won't be mentioned here). To update the table, every one of this player's records would have to be modified to reflect his new nickname.

Normalization By normalizing our data, we can ensure that our data tables are efficient and well-designed. This chapter doesn't go into detail about normalization, which is quite a complex topic. However, the basic idea is to break up your data into several related tables, so as to minimize the number of times you have to repeat the same data. The matchlog table contains a lot of repeating data. You can see that most of the repeating data is connected with individual players. For example, the player with the nickname Witblitz is mentioned twice in the table, and each time he s mentioned, all of his information (his player number, name, and phone number) is also included.

Normalization Therefore, it makes sense to pull the player details out into a separate players table, as follows: You can see that each player has just one record in this table. The playernumber field is the field that uniquely identifies each player (for example, there are two Davids, but they have different playernumber fields). The playernumber field is said to be the table's primary key.

Normalization Now that the player fields have been pulled out into the players table, the original matchlog table contains just one field dateplayed representing the date that a particular player participated in a match. Here comes the clever bit. We add the playernumber column back into the matchlog table

Normalization Now, by linking the values of the playernumber fields in both the player and matchlog tables, you can associate each player with the date (or dates) he played. The two tables are said to be joined by the playernumber field. The playernumber field in the matchlog table is known as a foreign key, because it references the primary key in the players table, and you can't have a playernumber value in the matchlog table that isn't also in the players table. Because the only repeating player information remaining in the matchlog table is the playernumber field, you've saved some storage space when compared to the original table. Furthermore, it's now easy to change the nickname of a player, because you only have to change it in one place: a single row in the players table.

Talking to Databases with SQL You're probably wondering how to actually retrieve information from these two tables, such as the nicknames of the players who played on March 3, 2004. This is where SQL comes in. SQL, the Structured Query Language, is a simple, standardized language for communicating with relational databases. SQL lets you do practically any database-related task, including creating databases and tables, as well as saving, retrieving, deleting, and updating data in databases.

MySQL Data Types When you create a database table which you do later in this lecture the type and size of each field must be defined. A field is similar to a PHP variable except that you can store only the specified type and size of data in a given field. For example, you can't insert characters into an integer field. MySQL supports three main groups of data types 1. numeric 2. date/time 3. string

Numeric Data Types You can store numbers in MySQL in many ways, but here we will only discuss two of them: Numeric Data Type Description Allowed Range of Values INT Normal - sized integer 2147483648 to 2147483647, or 0 to 4294967295 if UNSIGNED BIT 0 or 1 0 or 1 You can add the attribute UNSIGNED after a numeric data type when defining a field. An unsigned data type can only hold positive numbers.

Date and Time Data Types As with numbers, you can choose from a range of different data types to store dates and times. Here we only discuss two: Numeric Data Type Description Allowed Range of Values DATE Date 1 Jan 1000 to 31 Dec 9999 TIME Time 838:59:59 to 838:59:59

String Data Types MySQL lets you store strings of data in many different ways. Again we will only focus on two of those: Numeric Data Type Description Allowed Range of Values VARCHAR( n ) Variable-length string of up to n characters 0 65535 characters TEXT Normal-sized text field 0 65535 characters

SQL Statements To actually work with databases and tables, you use SQL statements. Common statements include: SELECT Retrieves data from one or more tables INSERT Inserts data into a table UPDATE Updates data in a table DELETE Deletes data from a table CREATE Creates a database, table or index ALTER Modifies the structure of a table DROP Wipes out a database or table

A Sample SQL Statement SELECT lastname, firstname FROM users WHERE firstname = John ; Take a closer look at the FROM and WHERE clauses in the query. The query returns any record from the users table where the value of the firstname field is John". Assuming there actually is a table called users in the database, the query's output which is called the result set might look like this: Simpleton John Smith John Thomas John

Setting Up MySQL The MySQL database system comes with a number of different programs. The two important ones that you learn about here are: The MySQL server: This is the database engine itself. The program is usually called mysqld or similar The MySQL command-line tool: You can use this tool to talk directly to the MySQL server so that you can create databases and tables, and add, view, and delete data. It's handy for setting up your databases and also for troubleshooting. The program name is simply mysql

Starting the MySQL Server If you installed WampServer on Windows, or MAMP on Mac OS X, then the MySQL server and command-line tool should already be installed on your computer. In fact, MySQL server may already be running, but if it's not, here's how to start it: WampServer on Windows: Examine the WampServer icon in your taskbar. If the icon is black and white, your Apache and MySQL servers should be running correctly. If the icon is part yellow or part red, then one or both of the servers aren't running. Click the icon to display the WampServer menu, then choose the Start All Services or Restart All Services option to start both the Apache and MySQL servers

Starting the MySQL Server MAMP on Mac OS X: Open the MAMP folder inside your Applications folder in Finder, then double-click the MAMP icon to launch the application. If the MySQL server has a red light to the left of it, click the Start Servers button to start up both the Apache and MySQL servers. Both lights should now be green

Creating a New Database To create a new database, all you have to do is use the CREATE DATABASE command. Type the following to create a new database called mydatabase : CREATE DATABASE mydatabase;

Creating a New Table As you know, tables are where you actually store your data. To start with, you'll create a very simple table, fruit, containing three fields: id (the primary key), name (the name of the fruit), and color (the fruit's color). CREATE TABLE fruit ( id INT UNSIGNED AUTO_INCREMENT, name VARCHAR(30), color VARCHAR(30), PRIMARY KEY (id) );

Creating a New Table You've created a table with the following three fields: id is the primary key. It uniquely identifies each row of the table. You created the id field as INT UNSIGNED, which means it can hold integer values up to 4,294,967,295. You also specified the keyword AUTO_INCREMENT. This ensures that, whenever a new row is added to the table, the id field automatically gets a new unique value (starting with 1). This means you don't have to specify this field's value when inserting data name will store the name of each fruit. It's created as VARCHAR(30), which means it can hold strings of up to 30 characters in length. color was created in the same way as name, and will be used to store the color of each fruit.

Adding Data to a Table To add a new row to a table, you use the SQL INSERT statement. In its basic form, an INSERT statement looks like this: INSERT INTO table VALUES ( value1, value2,... ); This inserts values into each of the fields of the table, in the order that the fields were created. Alternatively, you can create a row with only some fields populated. The remaining fields will contain NULL (if allowed), or in the case of special fields such as an AUTO_INCREMENT field, the field value will be calculated automatically. To insert a row of partial data, use: INSERT INTO table ( field1, field2,... ) VALUES ( value1, value2,... );

Adding Data to a Table Now try adding some fruit to your table. you can add three rows to the fruit table by inserting data into just the name and color fields (the id field will be filled automatically): INSERT INTO fruit ( name, color ) VALUES ( banana, yellow ); INSERT INTO fruit ( name, color ) VALUES ( tangerine, orange ); INSERT INTO fruit ( name, color ) VALUES ( plum, purple );

Reading Data From a Table To read data in SQL, you create a query using the SELECT statement. name of the table you want to read data from SELECT field1, field2,... FROM table WHERE condition; name of the fields you want to read from the table e.g age You can filter the results using the condition. e.g. age = 15

Reading Data From a Table If you want to read all fields from a table, you can use * instead of including all field names. SELECT * FROM fruit; This SQL statement returns all records in the fruit table. id name color 1 banana yellow 2 tangerine orange 3 plum purple

Reading Data From a Table Or we may use the following statement if we only want to see the name and color of all fruits. SELECT name, color FROM fruit; name banana tangerine plum color yellow orange purple

Reading Data From a Table Now if we want to retrieve a specific set of records with a given condition we can add WHERE conditions to our query: SELECT * FROM fruit where name = 'banana'; This query will return all records in the fruit table with the name 'banana' id name color 1 banana yellow

Reading Data From a Table Similarly we can specify conditions on other fields: SELECT * FROM fruit where id >= 2; This query will return all records in the fruit table where id >= 2 id name color 2 tangerine orange 3 plum purple

Reading Data From a Table We can also combine multiple conditions by using AND/OR operators: SELECT * FROM fruit where id >= 2 AND name = 'plum'; Here we will get a record with id >= 2 and the name = 'plum' id name color 3 plum purple

Updating Data in a Table You change existing data in a table with the UPDATE statement. As with the SELECT statement, you can (and usually will) add a WHERE clause to specify exactly which rows you want to update. If you leave out the WHERE clause, the entire table gets updated. UPDATE table SET field1 = value1, field2 = value2,... WHERE condition; name of the table you are updating pairs of field name and values e.g. age =15 will set the age to 15 for all records that the condition is true You can limit the set of records that you want to update by using a condition. e.g. name = 'sally'

Updating Data in a Table Here's how to use UPDATE to change values in your fruit table: UPDATE fruit SET name = 'grapefruit', color = 'yellow' WHERE id = 2; This SQL statement changes the name and color field values for the record with id = 2. If we read data in the table after this statement, the table looks like this: SELECT * FROM fruit; id name color 1 banana yellow 2 grapefruit yellow 3 plum purple

Deleting Data from a Table Deleting works in a similar way to updating. To delete rows, you use the DELETE statement. If you add a WHERE clause, you can choose which row or rows to delete; otherwise all the data in the table are deleted (though the table itself remains) DELETE FROM table WHERE condition; name of the table you want to delete data from You can limit the set of records that you want to delete by using a condition. e.g. name = 'sally'

Deleting Data from a Table Let's delete all records with id = 2 in our fruit table: DELETE FROM fruit where id = 2; This will delete one record from our fruit table. We can use SELECT to read data in our table : SELECT * FROM fruit; id name color 1 banana yellow 3 plum purple

Deleting Tables To delete a table entirely, use the DROP TABLE statement DROP TABLE table; This is the name of the table you want to delete entirely Note that this will delete the table and all records in it. This operation is not reversible.

Deleting Databases To delete a database entirely, use the DROP DATABASE statement DROP DATABASE db; This is the name of the database you want to delete entirely Note that this will delete the database and all tables and all records in it. This operation is not reversible.