* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Lab 1 Introduction to SQL Tools and Data Defination Language
Survey
Document related concepts
Microsoft Access wikipedia , lookup
Oracle Database wikipedia , lookup
Concurrency control wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Functional Database Model wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Ingres (database) wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
ContactPoint wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Clusterpoint wikipedia , lookup
Transcript
Introduction to Database Systems Lab-01 Introduction to SQL Tools and Data Definition Language (DDL) Lab 01: Introduction to SQL Tools and Data Definition Language Table of Contents 1. Introduction 3 2. Activity Time boxing 3 3. Objective of the experiment 3 4. Concept Map 3 4.1 4.2 4.3 4.4 3 4 4 4 4 4 4 4 4 5 5 4.5 4.6 4.7 4.8 Relational Data Model: Database Management System (DBMS): Relational Database Management System (RDBMS): SQL (Structured Query Language): 4.4.1 Data Manipulation Language 4.4.2 Data Definition Language 4.4.3 Data Control Language MySQL: PHP: PHPMyAdmin: XAMPP: 5. Homework before Lab 5 6. Procedure& Tools 5 6.1 6.2 6.3 7. Tools Installing and Setting Up XAMPP (MySQL, Apache) 6.2.1 Installation of XAMPP 6.2.2 Setting up XAMPP Walkthrough Tasks 6.3.1 Structured Query Language (SQL) and PHPMyAdmin 6.3.2 Data Definition Language (DDL) 6.3.3 Creating a database 6.3.4 Selecting a database 6.3.5 Creating a table in selected database 6.3.6 DataTypes 6.3.7 Constraints 6.3.8 Primary Key, Foreign Key 6.3.8.1. Primary Key 6.3.8.2. Foreign Key 6.3.9 ALTER TABLE and DROP 6.3.10 Viewing Database, Table and Field Information Practice Tasks 7.1 Practice Task 1 5 5 5 8 15 16 16 16 17 17 19 19 20 20 20 21 23 24 [Expected time = 65mins] 24 8. Evaluation Task (Unseen) [Expected time = 30mins for tasks] 25 9. Evaluation criteria 25 10. REFERENCES: 10.1 25 SQL-99 Complete, Really, by Peter Gulutzan & Trudy Pelzer. Department of Computer Science, C.U.S.T. 25 Page 2 Lab 01: Introduction to SQL Tools and Data Definition Language Lab 01: Introduction to SQL Tools and Data Definition Language 1. Introduction You are learning databases, database models, and database management systems particularly relational data model and relational database management system (RDBMS). In this lab, you will get familiar with the tools required for database management. You will use XAMPP application stack that includes MySQL Database Server, Apache Web Server, PHP interpreter, and PHPMyAdmin as a management system for MySQL Server. Relevant Lecture Material a) Revise Lecture No. 3 and 4 b) Text Book: Database Systems, A practical approach to design, implementation and management by Thomas Connolly, Carolyn Begg, Addison Wesley , Fifth Edition, 1. Read pages: 2. Read URL: i. http://www.tomjewett.com/dbdesign/dbdesign.php?page=ddldml.p hp 3. Revise the DDL 2. Activity Time boxing Table 1: Activity Time Boxing Task No. 6.2 6.3 7 8 Activity Name Setting-up and Setting XAMPP (MySQL, Apache) Walkthrough Tasks Practice tasks Evaluation Task Up Activity time 5mins Total Time 5mins 30mins 20 to 30mins for each task 60mins for all assigned task 60mins 50mins 60mins 3. Objective of the experiment To learn the installation, setup and usage of tools required for relational database management. To learn to implement a database schema in a database management system. 4. Concept Map Relational Data Model: The relational model is cantered on this idea of organization of data into collections of twodimensional tables called “relations.” Each row of the table is called a Tuple or Record. And each column is given a name and is called Attribute. 4.1 Department of Computer Science, C.U.S.T. Page 3 Lab 01: Introduction to SQL Tools and Data Definition Language Database Management System (DBMS): A database management system (DBMS) is a computer software application that interacts with the user, other applications, and the database itself to manage data in databases. A generalpurpose DBMS is designed to allow the definition, creation, querying, update, and administration of databases. 4.2 Relational Database Management System (RDBMS): A relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model. 4.3 SQL (Structured Query Language): SQL (Structured Query Language) is the standard language used for the retrieval and management of data in relational databases (RDBMS). It also supports database schema definition and modification. It is supported by all modern database management systems (e.g. Oracle, IBM DB2, Microsoft Access, Microsoft SQL Server, PostgresSQL, MySQL, etc.). 4.4 SQL is based on the relational model. The basis data structure in RDBMS is a table. SQL provides you the features to define tables, define constraints on tables, query for data in table, and change the data in table by adding, modifying, and removing data. SQL also supports grouping of data in multiple rows, combining tables and other features. SQL is high-level declarative language, quite easy to learn, allowing complex tasks on a database to be specified simply. SQL has a defined syntax that specifies how standard keywords can be combined to form valid SQL statements. SQL statements can be divided into three categories, according to their function: 4.4.1 Data Manipulation Language Statements that retrieve, insert, update, edit or delete data stored in database tables. These statements begin with the keywords: SELECT, INSERT, UPDATE or DELETE. 4.4.2 Data Definition Language Statements that create, modify, or destroy database objects (such as tables). These statements begin with the keywords: CREATE, ALTER or DROP. 4.4.3 Data Control Language Statements that authorize certain users to view, change or delete data. These statements begin with the keywords: GRANT or REVOKE. We do not consider data control in the lab exercises. MySQL: MySQL is a free, open-source, and the most popular relational database management system (RDBMS). 4.5 PHP: PHP is a server side scripting language, and a powerful tool for making dynamic and interactive 4.6 Department of Computer Science, C.U.S.T. Page 4 Lab 01: Introduction to SQL Tools and Data Definition Language Web applications. PHP is a widely-used, free, and open source. PHPMyAdmin: PHPMyAdmin is a free and open source tool written in PHP intended to handle the administration of MySQL with the use of a web browser. 4.7 XAMPP: XAMPP is a free and open source cross-platform web server solution stack package developed by Apache Friends. It includes MySQL, PHP, and PHPMyAdmin. 4.8 5. Homework before Lab Task1: You can study RDM & database? 6. Procedure& Tools Tools In this section tools installation and setup is defined. 6.1 6.2 Installing and Setting Up XAMPP (MySQL, Apache) 6.2.1 Installation of XAMPP Download XAMPP from http://www.apachefriends.org/en/xampp.html XAMPP for Windows exists in three different flavors. The “Installer” version is “probably the most comfortable way to install XAMPP” according to the XAMPP website. 6.2.1.1 Start the XAMPP installation Note that Windows 7,8, and 10 will warn that installing to the Program Files directory will keep XAMPP from being able to write to its directory due to UAC. Disabling UAC is not recommended. XAMPP can be installed to C:\XAMPP to avoid this issue or XAMPP can be given permission to run as Administrator. Figure 1 shows the dialogue box that gets the permission from the owner before installing XAMPP. Press ‘OK’ and proceed to next step. Figure 1: XAMPP 1.7.7 win32 Department of Computer Science, C.U.S.T. Page 5 Lab 01: Introduction to SQL Tools and Data Definition Language 6.2.1.2 The XAMPP installation starts with a splash screen as shown in figure 2. Click “Next”. Figure 2: XAMPP Setup Wizard 6.2.1.3 Figure 3 shows the next step of installation. Choose which directory to install XAMPP. Installing in D:\XAMPP can make installation easier. Figure 3: Xampp Startup 6.2.1.4 Installing Apache and MySQL as a service can give more options for running XAMPP when desired. When installed as services, the “services.msc” snap-in can be used to set the services to run “manually”. Running XAMPP services manually can help prevent opening security holes accidentally. Select installation of Apache and MySQL from the dialogue box as Department of Computer Science, C.U.S.T. Page 6 Lab 01: Introduction to SQL Tools and Data Definition Language shown in figure 4. Figure 4: XAMPP Options 6.2.1.5 Complete the installation. It may take a while. After the successful installation of XAMPP following screens will appear (refer to figure 5 and figure 6). Figure 5: Compleating the XAMPP Setup Wizard Department of Computer Science, C.U.S.T. Page 7 Lab 01: Introduction to SQL Tools and Data Definition Language Figure 6: Setup Complete Popup 6.2.2 Setting up XAMPP 6.2.2.1 After the installation is complete, open XAMPP control panel. The following window will appear (refer to figure 7). Start Apache and MySql. Figure 7: XAMP Control Panel 6.2.2.2 Before running Apache web server make sure Port 80 and 443 are not in use by any other application. If port 80 is being used it would display an error in XAMPP Control Panel. Department of Computer Science, C.U.S.T. Page 8 Lab 01: Introduction to SQL Tools and Data Definition Language Figure 8 : Xampp Startup In 80 is in use then you will click on “Config” button infront of “Apache”, select “httpd.conf” from the menu. Httpd.conf file will be opened in NotePad, Find “Listen 80” and change the port 80 to someother value of your choice. i.e. 8082. Figure 9 Department of Computer Science, C.U.S.T. Page 9 Lab 01: Introduction to SQL Tools and Data Definition Language Figure 10 In 443 is in use then you will click on “Config” button infront of “Apache”, select “httpdssl.conf” from the menu. Httpd-ssl.conf file will be opened in NotePad, Find “Listen 443” and change the port 443 to someother value of your choice. i.e. 444, Figure 11 Department of Computer Science, C.U.S.T. Page 10 Lab 01: Introduction to SQL Tools and Data Definition Language Figure 12 Figure 13 6.2.2.3 Start Apache and MySql. Department of Computer Science, C.U.S.T. Page 11 Lab 01: Introduction to SQL Tools and Data Definition Language Figure 14 6.2.2.4 Running PHPMyAdmin 6.2.2.4.1 Open any Browser i.e. Chrome, Firefox and Write the following URL in address bar. http://Localhost:8082/phpmyadmin Where 8082 is the port defined in Apache(httpd.conf) file in step 6.3.1.2. Figure 15 6.2.2.5 Setup Environment Variable Go to Control Panel > System and Security > System The Following screen will appear (refer to figure 8) and Click Advanced system settings Department of Computer Science, C.U.S.T. Page 12 Lab 01: Introduction to SQL Tools and Data Definition Language Figure 16: Advance System Settings Click Environment Variables. Figure 9 shows the window that will appear as the result of the action. Figure 17: System Properties Variable name PATH is available (refer to figure 10) double click it, otherwise click NEW Department of Computer Science, C.U.S.T. Page 13 Lab 01: Introduction to SQL Tools and Data Definition Language Figure 18: Environment Variables Copy the path of MySQL > BIN folder from your XAMPP installation folder as shown in figure 11. Figure 19: Path of bin folder Department of Computer Science, C.U.S.T. Page 14 Lab 01: Introduction to SQL Tools and Data Definition Language Paste the copied path in PATH variable opened from environment variables (refer to figure 10). Figure 20 : Edit User Variable Open Command prompt and Write command mysql or mysql -uroot then press enter Figure 21 : Command Prompt for starting mysql MySQL CLI is now running we can now start using it (refer to figure 13). 6.3 Walkthrough Tasks These tasks are designed to guide you to use the tools, implement the basic concepts of DDL. There are three basic statements within the DDL i.e. CREATE, DROP and ALTER. We will be Department of Computer Science, C.U.S.T. Page 15 Lab 01: Introduction to SQL Tools and Data Definition Language focusing on CREATE, USE and DROP statements in this lab. 6.3.1 Structured Query Language (SQL) and PHPMyAdmin SQL (Structured Query Language) is the standard language used for the retrieval and management of data in relational databases (RDBMS). We will use MySQL RDBMS that provides Console and GUI based tools to run or test our SQL Queries. We will use MySQL CLI and an open source web based GUI tool called “PHPMyAdmin” to execute our SQL queries. 6.3.2 Data Definition Language (DDL) SQL Using the MySQL CLI (Command Line Client) At the MySQL CLI, you can enter database commands followed by Enter. Prompts: At the MySQL prompt, you can enter database commands followed by Enter. There is also a set of commands that MySQL itself interprets. For a list of these commands, type help or \h at the mysql> prompt. Following Table shows some of the prompts you will see. Prompt mysql> -> '> "> Meaning Waiting for a command i.e ready for new command Waiting for the next line of a multiple-line command Waiting for the next line , waiting for completion of a string that begins with a single quote( “ ‘ “ ) Waiting for the next line of a string that starts with a double quote Note that: 1. Most MySQL commands end with a semicolon (;) 2. MySQL returns the total number of rows found, and the total time to execute the query. 3. Keywords may be entered in any letter case i.e uppercase or lowercase. You first need to create a database in which you will store your tables. This can be considered analogous to opening a blank database. To create a database we use the CREATE DATABASE command: 6.3.3 Creating a database CREATE DATABASE [IF NOT EXISTS] databaseName – Create a new database, IF NOT EXISTS is optional. Department of Computer Science, C.U.S.T. Page 16 Lab 01: Introduction to SQL Tools and Data Definition Language Figure 22: Create Database 6.3.4 Selecting a database Before starting to work (e.g. create tables, write queries etc.) with your database, you must select the database you are going to use. To do this, we use the USE command: USE databaseName -- select a database Figure 23: Show All Databases 6.3.5 Creating a table in selected database CREATE TABLE [IF NOT EXISTS] tableName ( columnName columnDataType columnConstraints, ... PRIMARY KEY(columnName), FOREIGN KEY (columnNmae) REFERENCES tableName (columnNmae) ) Department of Computer Science, C.U.S.T. Page 17 Lab 01: Introduction to SQL Tools and Data Definition Language Now, all the operations will be implemented on the database with the name retailer_db. There are no tables in this database yet. To create tables, we use the CREATE TABLE command: Figure 24: Create Table productlines The structure of the table can be checked through ‘describe’ command. Figure 25: Describe table Let’s create another table in the database. Department of Computer Science, C.U.S.T. Page 18 Lab 01: Introduction to SQL Tools and Data Definition Language Figure 26: Create Table products 6.3.6 DataTypes With the command above, we created a table with the name “productlines” which has 3 fields: productLine, textDescription and htmlDescription. In MySQL, we must specify a data type for each field. See Appendix A for complete list of MySQL datatypes, the most commonly used data types in MySQL are given in the table below: Data Type Description TINYINT, SMALLINT, MEDIUMINT, Integer values INT, BIGINT FLOAT, DOUBLE Floating-point values DECIMAL Decimal values CHAR Fixed length strings up to 255 characters VARCHAR Variable length strings up to 255 characters TINYBLOB, BLOB, MEDIUMBLOB, Longer blocks of text data LONGBLOB DATE, TIME, YEAR Date; time or duration; year values DATETIME Combined data and time values TIMESTAMP Timestamps ENUM One of a set of predefined values SET Zero or one 6.3.7 Constraints In addition to the data type of the fields, we can also specify field modifiers/constraints and keys when creating a table: Is the field allowed to be empty? We can specify this using the modifiers NULL and NOT NULL. Using the DEFAULT modifier we can specify a default value for the field. Department of Computer Science, C.U.S.T. Page 19 Lab 01: Introduction to SQL Tools and Data Definition Language AUTO_INCREMENT modifier enables us to create values for a field automatically. If we want the values for a field to be unique, we can use the UNIQUE modifier. 6.3.8 Primary Key, Foreign Key 6.3.8.1.Primary Key In the relational model, a table shall not contain duplicate rows, because that would create ambiguity in retrieval. To ensure uniqueness, each table should have a column (or a set of columns), called primary key,that uniquely identifies every record of the table. For example, a unique number customerID can be used as the primary key for the customers table; productCode for products table; isbn for books table. A primary key is called a simple key if it is a single column; it is called a composite key if it is made up of several columns. Most RDBMSs build an index on the primary key to facilitate fast search. The primary key is often used to relate to other tables. 6.3.8.2.Foreign Key A foreign key of a child table is used to reference the parent table. Foreign key constraint can be imposed to ensure so-called referential integrity - values in the child table must be valid values in the parent table. We define the foreign key when defining the child table, which references a parent table, as follows: -- Child table definition CREATE TABLE tableName ( ...... ...... CONSTRAINT constraintName FOREIGN KEY (columName) parentTableName (columnName) [ON DELETE RESTRICT | CASCADE | SET NULL | NO ACTION] reference action [ON UPDATE RESTRICT | CASCADE | SET NULL | NO ACTION] reference action ) REFERENCES -- On DELETE -- On UPDATE The last line in the CREATE TABLE command,”TYPE=InnoDB” or ”ENGINE=InnoDB”, selects a table type for the table movies. There are several table types in MySQL. By default the table type is MyISAM. Some of the tables’ types and the features they support are given below: Table Type MyISAM Features Default table type. Optimized for speed and reliability. Does not support foreign key constraints. In the future, MySQL AB is planning to implement foreign key constraints for MyISAM type tables. Department of Computer Science, C.U.S.T. Page 20 Lab 01: Introduction to SQL Tools and Data Definition Language InnoDB Successor to the MyISAM table type. The most sophisticated table type in MySQL. It supports foreign key constraints. One of the advanced table types in MySQL. Not easily portable between different operating systems. Lacks many optimization routines of the MyISAM tables. BDB (Berkeley DB) Now, let’s create two other tables: persons and roles. If you are using InnoDB tables, then you can define foreign keys using the FOREIGN KEY command as shown in figure 18. 6.3.9 ALTER TABLE and DROP We use the command ALTER TABLE to modify the design of the tables after we create them. There are various types of altering operations in MySQL: 6.3.9.1 Renaming a table: ALTER TABLE tableName RENAME TO newTableName OR RENAME TABLE tableName TO newTableName mysql> ALTER TABLE movies RENAME TO movie; or Figure 27: Rename Table Name Department of Computer Science, C.U.S.T. Page 21 Lab 01: Introduction to SQL Tools and Data Definition Language 6.3.9.2 Modifying a field: ALTER TABLE tableName CHANGE columnName newColumnName newColumnDataType newColumnConstraints, ... Figure 28 : Alter Attribute 6.3.9.3 Adding a new field: ALTER TABLE tableName ADD columnName columnDataType columnConstraints, ... Figure 29 : Add New Attribute 6.3.9.4 Deleting a field: ALTER TABLE tableName DROP columnName Department of Computer Science, C.U.S.T. Page 22 Lab 01: Introduction to SQL Tools and Data Definition Language Figure 30: Drop Attribute 6.3.9.5 Adding a primary key: ALTER TABLE tableName ADD PRIMARY KEY (columnName) 6.3.9.6 Changing table types: ALTER TABLE tableName ENGINE=engineName 6.3.9.7 Deleting a database: DROP DATABASE databaseName 6.3.9.8 Deleting a table: DROP TABLE tableName 6.3.10 Viewing Database, Table and Field Information 6.3.10.1 Viewing all available databases: SHOW DATABASES 6.3.10.2 Viewing all available tables from a databases: SHOW TABLES FROM tableName; 6.3.10.3 Viewing properties/schema of a table: DESCRIBE tableName Department of Computer Science, C.U.S.T. Page 23 Lab 01: Introduction to SQL Tools and Data Definition Language 7. Practice Tasks This section will provide more practice exercises which you need to finish during the lab. You need to finish the tasks in the required time. When you finish them, put these tasks in the following folder: \\dataserver\assignments$\Introduction to Database Management Systems\Lab1 Practice Task 1 [Expected time = 65mins] We will follow the database schema known as “Classic Models”. Your task is to create all the tables in database which are given in the figure 33. PRODUCTLINES (prorductLine, textDescription) PRODUCTS (productCode, productName, productLine, productVendor, productDescription, quantityInStock,buyPrice, Manufacturers_suggested_retail_price ) ORDERDETAILS (orderNumber,productCode, quantityOrdered, priceEach, orderLineNumber) ORDERS (orderNumber, orderDate, requiredDate, shippedDate, status, comments, customerNumber) CUSTOMERS (customerNumber, customerName, phone, addressLine1, city, state, postalCode, country, salesRepEmployeeNumber, creditLimit) PAYMENTS (cusotmerNumber, checkNumber, payementDate, amount) EMPLOYEES (employeeNumber, emloyeename, extension, email, officeCode, reportsTo, jobTitle, salary) OFFICES (officeCode, city, phone, addressLine1, country, postalCode) 7.1 Department of Computer Science, C.U.S.T. Page 24 Lab 01: Introduction to SQL Tools and Data Definition Language Figure 31: Database Design Diagram for "Classic Models" Schema 8. Evaluation Task (Unseen) [Expected time = 30mins for tasks] The lab instructor will give you unseen task depending upon the progress of the class. 9. Evaluation criteria The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has finished the complete/partial task(s). Table 3: Evaluation of the Lab Sr. No. Task No 1 6 7 2 3 8 Description Procedures and Tools Practice tasks and Testing Evaluation Tasks (Unseen) Marks 05 15 80 10. REFERENCES: 10.1 SQL-99 Complete, Really, by Peter Gulutzan & Trudy Pelzer. More examples for the SELECT command: Department of Computer Science, C.U.S.T. Page 25 Lab 01: Introduction to SQL Tools and Data Definition Language http://dev.mysql.com/doc/mysql/en/select.html MySQL operators: http://dev.mysql.com/doc/mysql/en/non-typed_operators.html Built-in functions: http://dev.mysql.com/doc/mysql/en/functions.html Joining tables: http://www.melonfire.com/community/columns/trog/article.php?id=148 Using subqeries: http://www.melonfire.com/community/columns/trog/article.php?id=204 Department of Computer Science, C.U.S.T. Page 26