Department of Computer Science & IT

Size: px
Start display at page:

Download "Department of Computer Science & IT"

Transcription

1 Department of Computer Science & IT Laboratory Manual (A Guide to MySQL) Prepared by: Muhammad Nouman Farooq Senior Lecturer Page 1 of 111

2 Course: Database Systems (CS-208 & CS-503) Table of Contents Lab Activity 1- Database Design Phase (ERD). 3-6 Lab Activity 2- SQL Syntax, Keywords, DDL Commands Lab Activity 3- Data Manipulation Language (DML) Commands Lab Activity 4- SQL Select Statement, Where Clause & Operators Lab Activity 5- SQL Statements & Alias Syntax Lab Activity 6- SQL Union Operator, Joining & Views Lab Activity 7- Normalization up to Third Normal Form (3-NF) Lab Activities-Detailed Review- MySQL Coding using Console Simulator Used: XAMPP Integrated Development Environment using CONSOLE and Navicat Graphical User Interface (GUI) Programming Language: SQL (Structured Query Language) Page 2 of 111

3 1. ERD Designing: Scenarios: Lab 1- Database Design Phase (ERD) 1. A player plays for a cricket team. In a cricket team, at least one or more player plays. 2. Each patient has at least one or more patient histories; each instance of patient history belongs to one patient. 3. An employee may be recorded as having many jobs; a particular job may be recorded as having been held by many employees. 4. A person is a citizen of a country. A country has more than one citizens. 5. A student may borrow some books from the library. A book in the library must be borrowed by a student. 6. A student takes at least one course. A course is taken by at least one student. Case Study 1: Odeon Cinema and other international cinemas have decided to install a centralized database. This database should keep information regarding cinemas including its name, address and phone number. Each CINEMA must have one or more THEATERS and each theater has a specific SHOWING TIME. During these showing times, a MOVIE is shown to the public. Page 3 of 111

4 Case Study 2: In a school, students are allocated to different classes. Each student must be allocated to exactly one class, and a class is formed by at least one or more than one student. Each class must be managed by several different students on different posts, namely Monitors and Prefect. Draw an E-R Diagram for the school, indicating Cardinalities. 2. ERD Reading: Scenario 1: Page 4 of 111

5 Scenario 2: Scenario 3: Scenario 4: Page 5 of 111

6 Scenario 5: Scenario 6: End of Lab Activity 1 Page 6 of 111

7 Lab Activity 2 SQL Syntax, Keywords, DDL Commands Step No. Details of the step Data Definition Language Commands: - It is used to communicate with database. DDL is used to: 1 o Create an object o Alter/Modify the structure of an object o To drop the object created. 2 The commands used are: Create, Alter, Drop, Truncate Integrity Constraint: - An integrity constraint is a mechanism used to prevent invalid data entry into 3 the table. It has enforcing the rules for the columns in a table. The types of the integrity constraints are: a) Domain Integrity b) Entity Integrity c) Referential Integrity Page 7 of 111

8 4 5 a) Domain Integrity This constraint sets a range and any violations that take place will prevent the user from performing the manipulation that caused the breach. It includes: Not Null Constraint: While creating tables, by default the rows can have null value, the enforcement of not null constraint in a table ensure that the table contains values. Principle of Null Values: o Setting null value is appropriate when the actual value is unknown, or when a value would not be meaningful. o A null value is not equivalent to a value of zero. o A null value will always evaluate to null in any expression. o When a column name is defined as not null, that column becomes a mandatory i.e., the user must enter data into it. o Not null Integrity constraint cannot be defined using the alter table command when the table contain rows. Check Constraint: Check constraint can be defined to allow only a particular range of values. When the manipulation violates this constraint, the record will be rejected. Check condition cannot contain sub queries. Page 8 of 111

9 b) Entity Integrity Maintains uniqueness in a record. An entity represents a table and each row of a table represents an instance of that entity. To identify each row in a table uniquely we need to use this constraint. There are 2 entity constraints: 6 Unique key Constraint It is used to ensure that information in the column for each record is unique, as with telephone or driver s license numbers. It prevents the duplication of value with rows of a specified column in a set of columns. A column defined with the constraint can allow null value. If unique key constraint is defined in more than one column i.e., combination of column cannot be specified. Maximum combination of columns that a composite unique key can contain is 16. Primary Key Constraint A primary key avoids duplication of rows and does not allow null values. It can be defined on one or more columns in a table and is used to uniquely identify each row in a table. These values should never be changed and should never be null. A table should have only one primary key. If a primary key constraint is assigned to more than one column or combination of column is said to be composite primary key, which can contain 16 columns. Page 9 of 111

10 7 c) Referential Integrity It enforces relationship between tables. To establish parent-child relationship between 2 tables having a common column definition, we make use of this constraint. To implement this, we should define the column in the parent table as primary key and same column in the child table as foreign key referring to the corresponding parent entry. Foreign key A column or combination of column included in the definition of referential integrity, which would refer to a referenced key. Referenced key It is a unique or primary key upon which is defined on a column belonging to the parent table. Page 10 of 111

11 SQL CREATE DATABASE Syntax DROP DATABASE IF EXISTS `dbname`; CREATE DATABASE IF NOT EXISTS `dbname`; USE `dbname`; 1. Create database northwind (Import northwind database) SQL CREATE TABLE + CONSTRAINT Syntax Drop TABLE IF EXISTS `database_name`.`table_name`; CREATE TABLE IF NOT EXISTS `database_name`.`table_name` ( columnname1 data_type AUTO_INCREMENT PRIMARY KEY, columnname2 data_type(size), columnname3 data_type NOT NULL, columnname4 data_type(size) DEFAULT 'anytext', UNIQUE (columnname3), -- CONSTRAINT `uk_columnname` UNIQUE (columnname3, columnname4..) -- PRIMARY KEY (columnname), /* CONSTRAINT pk_columnname PRIMARY KEY (columnname1, columnname2, ) for more than one columns */ /* PRIMARY KEY (columnname1, columnname2, ) -- Or use that syntax for more than one columns */ CONSTRAINT fk_columnname FOREIGN KEY (columnname) REFERENCES ParentTableName (columnname) ON update cascade on DELETE restrict, -- CHECK (columnname > 0), -- CHECK (columnname = text ) ); Page 11 of 111

12 2. Create the tables in the northwind database as per given SCHEMA Diagram Page 12 of 111

13 SQL SHOW DATABASE Syntax SHOW DATABASES show databases SQL SHOW TABLES Syntax SHOW TABLES SQL INSERT INTO Syntax The INSERT INTO statement is used to insert new records in a table. INSERT INTO `database_name`.`table_name` VALUES (value1,value2,value3,...); -- comment (single line) /* Multi line comment */ Insert Data Only in Specified Columns It is also possible to only insert data in specific columns. INSERT INTO `database_name`.`table_name` (column1,column2,column3) VALUES (value1,value2,value3), (value1,value2,value3) 3. Insert any 5 rows in all the tables of northwind database. Page 13 of 111

14 SQL ALTER TABLE Syntax To add a column in a table, use the following syntax: ALTER TABLE `database_name`.`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 `database_name`.`table_name` DROP COLUMN column_name To change the data type of a column in a table, use the following syntax: ALTER TABLE `database_name`.`table_name` MODIFY COLUMN column_name datatype 4. Practice to alter any column in any table in the northwind database. Page 14 of 111

15 The DROP TABLE Syntax The DROP TABLE statement is used to delete a table. DROP TABLE IF EXISTS `database_name`.`table_name` The DROP DATABASE Syntax The DROP DATABASE statement is used to delete a database. DROP DATABASE IF EXISTS `database_name` The TRUNCATE TABLE Syntax 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 `database_name`.`table_name` 5. Drop the table CUSTOMER from the northwind database. 6. Truncate the table PRODUCT. 7. Drop the northwind database. 8. Write a code for Lab 1-Database Design Phase (ERD) End of Lab Activity 2 Page 15 of 111

16 Lab Activity 3- Data Manipulation Language (DML) Commands Step no Details of the step DML COMMAND DML commands are the most frequently used SQL commands and is used to query and manipulate the existing database objects. Some of the commands are: - Insert, Select, Update and Delete Insert Command This is used to add one or more rows to a table. The values are separated by commas and the data types char and date are enclosed in apostrophes. The values must be entered in the same order as they are defined. Select Commands It is used to retrieve information from the table. It is generally referred to as querying the table. We can either display all columns in a table or only specify column from the table. Update Command It is used to alter the column values in a table. A single column may be updated or more than one column could be updated. Delete command After inserting row in a table, we can also delete them if required. The delete command consists of a FROM clause followed by an optional where clause. Page 16 of 111

17 The INSERT COMMAND Syntax Inserting a single row into a table: INSERT INTO `database_name`.`table name` VALUES (value list); Example: insert into customer.customer values (97, 'Nouman', '9km Bosan Road, ISP Main Campus, Multan', 'Multan', 'Punjab', 786) Skipping the fields while inserting: INSERT INTO database_name.tablename (column names to which data is to be inserted) VALUES (list of values); Note: Other way is to give null while passing the values. Page 17 of 111

18 The SELECT COMMAND Syntax Selects all rows from the table: SELECT * FROM database_name.tablename; Example: SELECT * FROM customer.customer; The retrieval of specific columns from a table: It retrieves the specified columns from the table SELECT column_name1,..,column_name n FROM database_name.table name; Example: SELECT id, name FROM customer.customer; Elimination of duplicates from the select clause: It prevents retrieving the duplicated values. Distinct keyword is to be used. SELECT DISTINCT col1, col2 FROM database_name.table name; Example: SELECT DISTINCT name FROM customer.customer; Page 18 of 111

19 Select command with where clause: To select specific rows from a table we include WHERE clause in the select command. It can appear only after the FROM clause. SELECT column_name1,..,column_name n FROM database_name.table name WHERE condition; Example: SELECT name FROM customer.customer WHERE id = 95; Select command with order by clause: SELECT column_name1,..,column_name n FROM database_name.table name WHERE condition ORDER BY colmnname; Example: SELECT name FROM customer.customer ORDER BY id; SELECT name FROM customer.customer ORDER BY id ASC; SELECT name FROM customer.customer ORDER BY id Desc; Select command to create a table (Inserting Existing Table Records): CREATE TABLE if not exists database_name.tablename AS SELECT * FROM existing_tablename; Example: CREATE TABLE customer.customer1 AS SELECT * FROM customer.customer; Select command to insert records: INSERT INTO database_name.tablename (SELECT columns FROM existing_tablename); Page 19 of 111

20 Example: INSERT INTO customer.customer1 (SELECT * FROM customer.customer); The UPDATE COMMAND Syntax: update database_name.tablename SET FIELD = values WHERE condition; Example: UPDATE customer.customer1 SET name = 'Arslan' WHERE id = 97; The DELETE COMMAND Syntax: DELETE FROM database_name.tablename WHERE conditions; Example: DELETE FROM customer.customer1 WHERE ID = 98; 1. Import CUSTOMER database (CUSTOMER database for lab activity 3) and Insert your meaningful record into Customer table 2. Select customer id, name from the customer table 3. CREATE CUSTOMER1 table using above syntax & UPDATE the customer1 table to set the state to NY of all customer ranging from ID 1 to Delete only those who are living in state NY 5. List the records in the CUSTOMER table order by ID into descending order 6. Display only that customer whose ID is from 25 to Display STATE from the table CUSTOMER avoiding the duplicated values. End of Lab Activity 3 Page 20 of 111

21 Lab Activity 4- SQL Select Statement, Where Clause & Operators The SQL 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. SQL SELECT Syntax To select the specific data SELECT column_name,column_name FROM database_name.table_name To select the entire data in a table SELECT * FROM database_name.table_name 1. Import CUSTOMER database (CUSTOMER database for lab activity 4) and Find the "CustomerName" and "City" columns from the "Customer" table. 2. Find all the columns from the "Customer" table The SQL SELECT DISTINCT Statement In a table, a column may contain many duplicate values; and sometimes you only want to list the different (distinct) values. The DISTINCT keyword can be used to return only distinct (different) values. SQL SELECT DISTINCT Syntax SELECT DISTINCT column_name,column_name FROM database_name.table_name 3. Find only the distinct values from the "City" columns from the "Customer" table Page 21 of 111

22 The SQL WHERE Clause The WHERE clause is used to filter records. The WHERE clause is used to extract only those records that fulfill a specified criterion. SQL WHERE Syntax SELECT column_name,column_name FROM database_name.table_name WHERE column_name value 4. Find all the customer from the city "New York", in the "Customer" table. 5. Find all the customer in the customer tables whose CustomerID=1. Page 22 of 111

23 Operators in the WHERE Clause The following operators can be used in the WHERE clause: Operator Description = Equal <> Not equal. Note: In some versions of SQL this operator may be written as!= > Greater than < Less than >= Greater than or equal <= Less than or equal BETWEEN LIKE IN Between an inclusive range Search for a pattern To specify multiple possible values for a column Page 23 of 111

24 The SQL LIKE Operator The LIKE operator is used to search for a specified pattern in a column. SQL LIKE Syntax SELECT column_name(s) FROM database_name.table_name WHERE column_name LIKE pattern SELECT * FROM table_name WHERE column_name LIKE pattern SQL LIKE Operator Examples The following SQL statement selects all customers with a City starting with the letter "s": Try it yourself SELECT * FROM customer.customer WHERE City LIKE 's%'; Tip: The "%" sign is used to define wildcards (missing letters) both before and after the pattern. The following SQL statement selects all customers with a City ending with the letter "s": Try it yourself SELECT * FROM customer.customer WHERE City LIKE '%s' The following SQL statement selects all customer with a Country containing the pattern "land": Try it yourself SELECT * FROM customer.customer WHERE city LIKE '%land%' Page 24 of 111

25 Using the NOT keyword allows you to select records that do NOT match the pattern. The following SQL statement selects all customer with Country NOT containing the pattern "land": Try it yourself SELECT * FROM customer.customer WHERE city NOT LIKE '%land%' SQL Wildcard Characters In SQL, wildcard characters are used with the SQL LIKE operator. SQL wildcards are used to search for data within a table. With SQL, the wildcards are: Wildcard Description % A substitute for zero or more characters _ [charlist] [^charlist] or [!charlist] A substitute for a single character Sets and ranges of characters to match Matches only a character NOT specified within the brackets Page 25 of 111

26 Using the SQL % Wildcard The following SQL statement selects all customer with a City starting with "b": Try it yourself SELECT * FROM customer.customer WHERE City LIKE 'b%' The following SQL statement selects all customer with a City containing the pattern "es": Try it yourself SELECT * FROM customer.customer WHERE City LIKE '%es%' Using the SQL _ Wildcard The following SQL statement selects all customer with a City starting with any character, followed by "oston": Try it yourself SELECT * FROM customer.customer WHERE City LIKE '_oston' The following SQL statement selects all customer with a City starting with "L", followed by any character, followed by "s", followed by any character, followed by "Vegas": Try it yourself SELECT * FROM customer.customer WHERE City LIKE 'L_s_Vegas' Page 26 of 111

27 Using the SQL [charlist] Wildcard The following SQL statement selects all customer with a City starting with "l", "a", or "s": Try it yourself SELECT * FROM customer.customer WHERE City LIKE 'LAS%' The following SQL statement selects all customer with a City starting with "holl": Try it yourself SELECT * FROM customer.customer WHERE City LIKE 'holl%' The following SQL statement selects all customer with a City NOT starting with "h", o", l", or "l": Try it yourself SELECT * FROM customer.customer WHERE City NOT LIKE 'holl%' Page 27 of 111

28 The IN Operator The IN operator allows you to specify multiple values in a WHERE clause. SQL IN Syntax SELECT column_name(s) FROM database_name.table_name WHERE column_name IN (value1,value2,...) IN Operator Example The following SQL statement selects all customer with a City of "Paris" or "London": Try it yourself SELECT * FROM customer.customer WHERE City IN ('Paris','London') Page 28 of 111

29 The SQL BETWEEN Operator The BETWEEN operator selects values within a range. The values can be numbers, text, or dates. SQL BETWEEN Syntax SELECT column_name(s) FROM database_name.table_name WHERE column_name BETWEEN value1 AND value2 SQL NOT BETWEEN Syntax SELECT column_name(s) FROM database_name.table_name WHERE column_name NOT BETWEEN value1 AND value2 6. Find all addresses with a id BETWEEN 15 and Display the addresses outside the range of 15 and 25, use NOT BETWEEN BETWEEN Operator with IN Example The following SQL statement selects all customer with a Id BETWEEN 1 and 20, but customer with a id of 1, 2, or 3 should not be displayed: Try it yourself SELECT * FROM customer.customer WHERE (id BETWEEN 1 AND 10) AND NOT id IN (1,2,3) Page 29 of 111

30 BETWEEN Operator with Text Value Example The following SQL statement selects all customer with a city beginning with any of the letter BETWEEN 'D' and 'I': Try it yourself SELECT * FROM customer.customer WHERE city BETWEEN 'D' AND 'I' NOT BETWEEN Operator with Text Value Example The following SQL statement selects all customer with a city beginning with any of the letter NOT BETWEEN 'D' and 'I': Try it yourself SELECT * FROM customer.customer WHERE city NOT BETWEEN 'D' AND 'I' BETWEEN Operator with Date Value Example The following SQL statement selects all customer with an zip BETWEEN '2104' and '3320': Try it yourself SELECT * FROM customer.customer WHERE zip BETWEEN 2104 AND 3320 Page 30 of 111

31 Notice that the BETWEEN operator can produce different result in different databases! In some databases, BETWEEN selects fields that are between and excluding the test values. In other databases, BETWEEN selects fields that are between and including the test values. And in other databases, BETWEEN selects fields between the test values, including the first test value and excluding the last test value. Therefore: Check how your database treats the BETWEEN operator! 8. Practice and Display every given above Syntax in Customer Table End of Lab Activity 4 Page 31 of 111

32 Lab Activity 5- SQL Statements & Alias Syntax The SQL AND & OR Operators The AND & OR operators are used to filter records based on more than one condition. The AND operator displays a record if both the first condition AND the second condition are true. The OR operator displays a record if either the first condition OR the second condition is true. SQL AND Syntax SELECT * FROM database_name.table_name WHERE column_name=value AND column_name=value SQL OR Syntax SELECT * FROM database_name.table_name WHERE column_name=value OR column_name=value 1. Find all customers from the country "Germany" AND the city "Berlin", in the "Customers" table. 2. Find all customers from the city "Berlin" OR "München", in the "Customers" table. Page 32 of 111

33 Combining AND & OR You can also combine AND and OR (use parenthesis to form complex expressions). The following SQL statement selects all customers from the country "Germany" AND the city must be equal to "Berlin" OR "München", in the "Customers" table: Try it yourself SELECT * FROM customer.customer WHERE Country='Germany' AND (City='Berlin' OR City='München') The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set by one or more columns. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword. SQL ORDER BY Syntax SELECT column_name, column_name FROM database_name.table_name ORDER BY column_name ASC DESC, column_name ASC DESC 3. Find all customers from the "Customers" table, sorted by the "Country" column. 4. Find all customers from the "Customers" table, sorted DESCENDING by the "Country" column. 5. Find all customers from the "Customers" table, sorted by the "Country" and the "CustomerName" column. 6. Find all customers from the "Customers" table, sorted ascending by the "Country" and descending by the "CustomerName" column Page 33 of 111

34 The SQL UPDATE Statement The UPDATE statement is used to update existing records in a table. SQL UPDATE Syntax UPDATE database_name.table_name SET column1=value1,column2=value2,... WHERE some_column=some_value Notice the WHERE clause in the SQL UPDATE statement! The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated! 7. Update the customer "Alfreds Futterkiste" with a new contact person and city. The SQL DELETE Statement The DELETE statement is used to delete rows in a table. SQL DELETE Syntax DELETE FROM database_name.table_name WHERE some_column=some_value Notice the WHERE clause in the SQL DELETE statement! The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted! 8. Delete the customer "Alfreds Futterkiste" from the "Customers" table Page 34 of 111

35 The SQL LIMIT Clause The LIMIT clause is used to specify the number of records to return. The LIMIT clause can be very useful on large tables with thousands of records. Returning a large number of records can impact on performance. Note: Not all database systems support the LIMIT clause. MySQL LIMIT Syntax SELECT column_name(s) FROM database_name.table_name LIMIT number 9. Find the two first records from the "Customers" table. Page 35 of 111

36 SQL Aliases SQL aliases are used to give a database table, or a column in a table, a temporary name. Basically, aliases are created to make column names more readable. SQL Alias Syntax for Columns SELECT column_name AS alias_name FROM database_name.table_name SQL Alias Syntax for Tables SELECT column_name(s) FROM database_name.table_name AS alias_name Alias Example for Table Columns The following SQL statement specifies two aliases, one for the CustomerName column and one for the ContactName column. Tip: It requires double quotation marks or square brackets if the column name contains spaces: Try it yourself SELECT CustomerName AS Customer, ContactName AS [Contact Person] FROM Customers In the following SQL statement, we combine four columns (Address, City, PostalCode, and Country) and create an alias named "Address": Try it yourself SELECT CustomerName, CONCAT (Address,', ',City,', ',PostalCode,', ',Country) AS Address FROM Customers Page 36 of 111

37 Alias Example for Tables The following SQL statement selects all the orders from the customer with CustomerID=4 (Around the Horn). We use the "Customers" and "Orders" tables, and give them the table aliases of "c" and "o" respectively (Here we have used aliases to make the SQL shorter): Try it yourself SELECT o.orderid, o.orderdate, c.customername FROM customer.customer AS c, Orders AS o WHERE c.customername="around the Horn" AND c.customerid=o.customerid The same SQL statement without aliases: Try it yourself SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName FROM customer.customer, Orders WHERE Customer.CustomerName="Around the Horn" AND Customer.CustomerID=Orders.CustomerID Aliases can be useful when: There are more than one table involved in a query Functions are used in the query Column names are big or not very readable Two or more columns are combined together End of Lab Activity 5 Page 37 of 111

38 Lab Activity 6- SQL Union Operator, Joining & Views SQL JOIN An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them. Different SQL JOINs CROSS JOIN: Cross Join returns the Cartesian product of rows from tables in the join. INNER JOIN: Returns all rows when there is at least one match in BOTH tables LEFT JOIN: Return all rows from the left table, and the matched rows from the right table RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table FULL JOIN: Return all rows when there is a match in ONE of the tables Page 38 of 111

39 SQL CROSS JOIN Keyword Cross Join returns the Cartesian product of rows from tables in the join. SQL CROSS JOIN Syntax SELECT column_name(s) FROM database_name.table1 CROSS JOIN database_name.table2 ORDER BY `CROS`.`table_name that will be in both table s` ASC -- Example of an Explicit Cross Join OR SELECT * FROM database_name.table1. database_name.table2 ORDER BY `database_name`.`table_name that will be in both table s` ASC -- Example of an Implicit Cross Join Try it yourself SELECT * from JOINING.EMPLOYEE CROS JOIN JOINING.Department ORDER BY `CROS`.`DepartmentID` ASC -- Example of an Explicit Cross Join SELECT * from `JOINING`.`EMPLOYEE`, `JOINING`.`Department` ORDER BY `EMPLOYEE`.`DepartmentID` ASC; -- Example of an Implicit Cross Join Page 39 of 111

40 SQL INNER JOIN Keyword The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns in both tables. SQL INNER JOIN Syntax SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name=table2.column_name OR SELECT column_name(s) FROM table1 JOIN table2 ON table1.column_name=table2.column_name PS! INNER JOIN is the same as JOIN. SQL INNER JOIN Example The following SQL statement will return all customers with orders: Try it yourself SELECT Customers.CustomerName, Orders.OrderID FROM Customers INNER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns. If there are rows in the "Customers" table that do not have matches in "Orders", these customers will NOT be listed. Page 40 of 111

41 SQL LEFT JOIN Keyword The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match. SQL LEFT JOIN Syntax SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name=table2.column_name OR SELECT column_name(s) FROM table1 LEFT OUTER JOIN table2 ON table1.column_name=table2.column_name PS! In some databases LEFT JOIN is called LEFT OUTER JOIN. SQL LEFT JOIN Example The following SQL statement will return all customers, and any orders they might have: Try it yourself SELECT Customers.CustomerName, Orders.OrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName Note: The LEFT JOIN keyword returns all the rows from the left table (Customers), even if there are no matches in the right table (Orders). Page 41 of 111

42 SQL RIGHT JOIN Keyword The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in the left table (table1). The result is NULL in the left side when there is no match. SQL RIGHT JOIN Syntax SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name=table2.column_name OR SELECT column_name(s) FROM table1 RIGHT OUTER JOIN table2 ON table1.column_name=table2.column_name PS! In some databases, RIGHT JOIN is called RIGHT OUTER JOIN. SQL RIGHT JOIN Example The following SQL statement will return all employees, and any orders they have placed: Try it yourself SELECT Orders.OrderID, Employees.FirstName FROM Orders RIGHT JOIN Employees ON Orders.EmployeeID=Employees.EmployeeID ORDER BY Orders.OrderID Note: The RIGHT JOIN keyword returns all the rows from the right table (Employees), even if there are no matches in the left table (Orders). Page 42 of 111

43 SQL FULL OUTER JOIN Keyword The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2). The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins. Important Note: We don't have FULL JOINS on MySQL, but we can sure use this query to get our desired result as per full join definition. SQL FULL OUTER JOIN Syntax SELECT * FROM t1 -- Syntax with Two Tables t1 and t2 LEFT JOIN t2 ON t1.column_name = t2.column_name UNION ALL SELECT * FROM t1 RIGHT JOIN t2 ON t1.column_name = t2.column_name SQL FULL OUTER JOIN Example The following SQL statement selects all customers, and all orders: SELECT * from `JOINING`.`EMPLOYEE` LEFT JOIN `JOINING`.`DEPARTMENT` ON `EMPLOYEE`.`DEPARTMENTID` = `DEPARTMENT`.`DEPARTMENTID` UNION ALL SELECT * FROM `JOINING`.`EMPLOYEE` RIGHT JOIN ON `EMPLOYEE`.`DEPARTMENTID` = `DEPARTMENT`.`DEPARTMENTID` ORDER BY `DEPARTMENT`.`DEPARTMENTID` ASC; Note: The FULL OUTER JOIN keyword returns all the rows from the left table (Customers), and all the rows from the right table (Orders). If there are rows in "Customers" that do not have matches in "Orders", or if there are rows in "Orders" that do not have matches in "Customers", those rows will be listed as well. Page 43 of 111

44 Lab Assignment: - 1. Create three tables named EMPLOYEE_DETAIL & SALARY & PHONE_NUMBER in a database named EMPLOYEE via code as shown in figure: 2. Implement all Joining Queries on the above created database named EMPLOYEE_DETAIL Page 44 of 111

45 The SQL UNION Operator The UNION operator is used to combine the result-set of two or more SELECT statements. Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order. SQL UNION Syntax SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2 Note: The UNION operator selects only distinct values by default. To allow duplicate values, use the ALL keyword with UNION. SQL UNION ALL Syntax SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2 PS: The column names in the result-set of a UNION are usually equal to the column names in the first SELECT statement in the UNION. Page 45 of 111

46 SQL UNION Example The following SQL statement selects all the different cities (only distinct values) from the "Customers" and the "Suppliers" tables: Try it yourself SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY City Note: UNION cannot be used to list ALL cities from the two tables. If several customers and suppliers share the same city, each city will only be listed once. UNION selects only distinct values. Use UNION ALL to also select duplicate values! SQL UNION ALL Example The following SQL statement uses UNION ALL to select all (duplicate values also) cities from the "Customers" and "Suppliers" tables: Try it yourself SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers ORDER BY City Page 46 of 111

47 SQL UNION ALL With WHERE The following SQL statement uses UNION ALL to select all (duplicate values also) German cities from the "Customers" and "Suppliers" tables: Try it yourself SELECT City, Country FROM Customers WHERE Country='Germany' UNION ALL SELECT City, Country FROM Suppliers WHERE Country='Germany' ORDER BY City Page 47 of 111

48 The SQL SELECT INTO Statement The SELECT INTO statement selects data from one table and inserts it into a new table. SQL SELECT INTO Syntax We can copy all columns into the new table: SELECT * INTO newtable [IN externaldb] FROM table1 Or we can copy only the columns we want into the new table: SELECT column_name(s) INTO newtable [IN externaldb] FROM table1 The new table will be created with the column-names and types as defined in the SELECT statement. You can apply new names using the AS clause. SQL SELECT INTO Examples Create a backup copy of Customers: SELECT * INTO CustomersBackup2013 FROM Customers Use the IN clause to copy the table into another database: SELECT * INTO CustomersBackup2013 IN 'Backup.mdb' FROM Customers Copy only a few columns into the new table: SELECT CustomerName, ContactName INTO CustomersBackup2013 FROM Customers Page 48 of 111

49 Copy only the German customers into the new table: SELECT * INTO CustomersBackup2013 FROM Customers WHERE Country='Germany' Copy data from more than one table into the new table: SELECT Customers.CustomerName, Orders.OrderID INTO CustomersOrderBackup2013 FROM Customers LEFT JOIN Orders ON Customers.CustomerID=Orders.CustomerID Tip: The SELECT INTO statement can also be used to create a new, empty table using the schema of another. Just add a WHERE clause that causes the query to return no data: SELECT * INTO newtable FROM table1 WHERE 1=0 Page 49 of 111

50 The SQL INSERT INTO SELECT Statement The INSERT INTO SELECT statement selects data from one table and inserts it into an existing table. Any existing rows in the target table are unaffected. SQL INSERT INTO SELECT Syntax We can copy all columns from one table to another, existing table: INSERT INTO table2 SELECT * FROM table1 Or we can copy only the columns we want to into another, existing table: INSERT INTO table2 (column_name(s)) SELECT column_name(s) FROM table1 SQL INSERT INTO SELECT Examples Copy only a few columns from "Suppliers" into "Customers": Try it yourself INSERT INTO Customers (CustomerName, Country) SELECT SupplierName, Country FROM Suppliers Copy only the German suppliers into "Customers": Try it yourself INSERT INTO Customers (CustomerName, Country) SELECT SupplierName, Country FROM Suppliers WHERE Country='Germany' Page 50 of 111

51 SQL CREATE VIEW Statement In SQL, a view is a virtual table based on the result-set 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. SQL CREATE VIEW Syntax CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition 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 SQL CREATE VIEW Examples If you have the Northwind database, you can see that it has several views installed by default. The view "Current Product List" lists all active products (products that are not discontinued) from the "Products" table. The view is created with the following SQL: CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName FROM Products WHERE Discontinued=No Page 51 of 111

52 We can query the view above as follows: SELECT * FROM [Current Product List] Another view in the Northwind sample database selects every product in the "Products" table with a unit price higher than the average unit price: CREATE VIEW [Products Above Average Price] AS SELECT ProductName,UnitPrice FROM Products WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products) We can query the view above as follows: SELECT * FROM [Products Above Average Price] Another view in the Northwind database calculates the total sale for each category in Note that this view selects its data from another view called "Product Sales for 1997": CREATE VIEW [Category Sales For 1997] AS SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales FROM [Product Sales for 1997] GROUP BY CategoryName We can query the view above as follows: SELECT * FROM [Category Sales For 1997] We can also add a condition to the query. Now we want to see the total sale only for the category "Beverages": SELECT * FROM [Category Sales For 1997] WHERE CategoryName='Beverages' Page 52 of 111

53 SQL Updating a View You can update a view by using the following syntax: SQL CREATE OR REPLACE VIEW Syntax CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition Now we want to add the "Category" column to the "Current Product List" view. We will update the view with the following SQL: CREATE OR REPLACE VIEW [Current Product List] AS SELECT ProductID,ProductName,Category FROM Products WHERE Discontinued=No SQL Dropping a View You can delete a view with the DROP VIEW command. SQL DROP VIEW Syntax DROP VIEW view_name End of Lab Activity 6 Page 53 of 111

54 Lab Activity 7- Normalization up to Third Normal Form (3-NF) Database Normalization up to 3-NF: Lab Assignment: - 1. Create and Normalize the following given table s up to 3-NF via Code: 2. Name of a database must be ADVISOR_SCHEDULE End of Lab Activity 7 Page 54 of 111

55 Lab Activities Detailed Review- MySQL Coding Using Console XAMPP: - XAMPP stands for Cross-Platform (X), Apache (A), MySQL (M), PHP (P) and Perl (P). It is a simple, light-weighted Apache server that makes it extremely easy for developers to create a local http server with just few clicks. An integrated development environment (IDE) is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of a source code editor, build automation tools and a debugger/tester of Program/Execution of program. After Installation of XAMPP Server Starting Services of Apache and MySQL (the sign changes from red to green): - Page 55 of 111

56 We can access the local server via graphical user interface (GUI) by click on the Admin button of MySQL. phpmyadmin: - It is a free and open source tool/simulator written in PHP intended to handle the administration of MySQL or MariaDB (DBMS Engines) with the use of a web browser. It can perform various tasks such as creating, modifying or deleting databases, tables, fields or rows; executing SQL statements; or managing users and permissions. Apache: - It is the most widely used web server software. Developed and maintained by Apache Software Foundation, Apache is an open source software available for free. It runs on 67% of all webservers in the world. It is fast, reliable, and secure. Page 56 of 111

57 We can access the local server via Domain Name directly in the browser that is by default (after starting services of Apache and MySQL): - localhost/phpmyadmin Also, we can access the local server via loopback IP Address in web browser that is by default (after starting services of Apache and MySQL): - Page 57 of 111

58 /phpmyadmin : - Page 58 of 111

59 This is a loopback IP address (Special IP address) that is used to access the local server. Drop Command: - This command is disable by default. So, to enable it follow the following process: 1. Go To: - C:\xampp\phpmyadmin\libraries 2. Open the file called "config.default.php" 3. Go to line 653 and change $cfg['allowuserdropdatabase'] = false; to true 4. Restart the server to see the changes Securing Server ROOT USER by Implementing Password using the following steps: - Go into Edit Privileges Page 59 of 111

60 Then, Go into Change Password: - Page 60 of 111

61 Than: - Page 61 of 111

62 Go into installed directory of XAMPP: C:\xampp\phpMyAdmin Open: config.inc And Change: - config to cookie Then, Change and Type that password that already assigned in Server: - Page 62 of 111

63 Data Definition Language Commands (DDL Commands): - Page 63 of 111

64 1. CREATE 2. ALTER 3. DROP 4. TRUNCATE Data Manipulation Language Commands (DML Commands): - 1. INSERT 2. SELECT 3. UPDATE 4. DELETE SQL Keywords: - 1. MODIFY 2. SHOW 3. USE SQL (Sequel) is Case Insensitive SQL (Sequel) is Open Source Language that means FREE FOR ALL Page 64 of 111

65 Double Hyphen -- is used for single line comment /* these backslash steric and steric backslash is used for multi-line comment */ # is NOT a standard SQL Comment ; -- semi colon is used to terminate a query) /* When we write a single SQL Query than we may not terminate it using Semi Colon ; */ Conditions: these given below conditions are used to make any query in MySQL error free and efficient IF EXISTS and IF NOT EXISTS Identifier: - ` Page 65 of 111

66 In MySQL, an Identifier is used to separate database and table name. Identifier is a sequence of characters used to identify or refer to a program or an element, such as a variable or a set of data, within it. `Database_Name` /* Advantage of Using Identifier in MySQL Coding: Identifier is a sequence of characters used to identify or refer to a program or an element, such as a variable or a set of data, within it for Example If we want to create a Database with the name CREATE. We cannot create it without the use of an Identifier because CREATE is a Command in MySQL. */ -- Example: - "The following Command cannot be executed without Identifier" /* drop database if exists `create`; CREATE DATABASE IF NOT EXISTS CREATE; */ /* But; Example: - "The following Command can be executed with Identifier" */ drop database if exists `create`; CREATE DATABASE IF NOT EXISTS `CREATE`; Qualifier Character: -. In MySQL the Qualifier Character is a separate token and need not be connecting with the associated identifiers. For example, `table_name`.`column_name` and `table_name`. `column_name` are equivalen -- Without Selecting any database, we can also run some Queries: - Page 66 of 111

67 select ; -- We can perform calculations in Console/Command line Interface (CLI) select ; -- We can perform calculations in Console/CLI select 26 mod 26; -- We can perform calculations in Console/CLI select 27 mod 26; -- We can perform calculations in Console/CLI select "This is Database Systems lab "; -- We can write and show output in Console/CLI select "HELLO CLASS!!"; -- We can write and show output in Console/CLI select "this subject is just amazing"; -- We can write and show output in Console/CLI SELECT SYSDATE(); -- SYSDATE() Function returns current date & time of the system Show Databases; -- To show all databases in a Server -- Use database_name -- Syntax to use a specific database Page 67 of 111

68 drop database if exists `LAB`; -- Use IF EXISTS to prevent an error from occurring for databases that do not exist create database `LAB`; -- Creating a database VIA Single Query (Double Hyphen for Comments) ( use `lab`; create table `lab`.`test` `testno` int (3) not null auto_increment, `testid` int(3), `testname` varchar (20), `CREATE` int (20), -- If we want to Create a CREATE TABLE we must use identifier primary key (`testno`, `testid`, `testname`) /* To create multiple primary keys (Composite Primary Key in a table; Use the given syntax) */ /* ); The DESCRIBE and EXPLAIN statements are synonyms, used either to obtain information about table structure via code. */ DESCRIBE `lab`.`test`; drop database `LAB`; -- to show the structure of a table -- To delete a Database Page 68 of 111

69 create database IF NOT EXISTS `LAB`; -- Creating a database VIA Single but efficient Query drop database if exists `LAB`; -- To delete a Database Query but Efficient than previous query drop database if exists `lab1`; -- To delete a Database Query create database if not exists `LAB1`; /* Creating, Selecting and Inserting Values in Table VIA Single Query (Double Hyphen for Comments) */ use `lab1`; create table `lab1`.`test` /* Using Qualifier Character to quickly create a table in a selected database via single query */ ( `testid` int(2) not null PRIMARY KEY, `test1id` int(2), `testname` varchar (20) ); create table `lab1`.`test1` ( `test1id` int(2), `testid` int(2), Page 69 of 111

70 `test1name` varchar (20), constraint `fk_1` FOREIGN KEY (`testid`) references `lab1`.`test` (`testid`) ON DELETE RESTRICT ON UPDATE CASCADE; ); ALTER TABLE `lab1`.`test` ADD testmarks float not null; -- To add a column in a table, use the following syntax via Query -- DESCRIBE `lab1`.`test`; ALTER TABLE `lab1`.`test1` ADD PRIMARY KEY(`test1Id`); -- To alter and add a primary key in 2nd table, use the following syntax via Query -- EXPLAIN `lab1`.`test1`; ALTER TABLE `lab1`.`test` ADD CONSTRAINT `fk_test` FOREIGN KEY (`test1id`) REFERENCES `lab1`.`test1`(`test1id`) ON DELETE RESTRICT ON UPDATE RESTRICT; -- By Altering and adding a foreign key constraint in first table, use the following syntax via Query -- EXPLAIN `lab1`.`test`; Page 70 of 111

71 ALTER TABLE `lab1`.`test1` DROP FOREIGN KEY `fk_1`; ALTER TABLE `lab1`.`test1` ADD CONSTRAINT `fk_test1` FOREIGN KEY (`testid`) REFERENCES `lab1`.`test`(`testid`) ON DELETE RESTRICT ON UPDATE RESTRICT; -- To change the name of the foreign key constraint in a table, firstly drop the Constraint of Foreign key than again write the whole query as given /* Let's look at the ON UPDATE clause: ON UPDATE RESTRICT: the default: if you try to update a company_id in table COMPANY the engine will reject the operation if one USER at least links on this company. ON UPDATE NO ACTION: same as RESTRICT. ON UPDATE CASCADE: the best one usually: if you update a company_id in a row of table COMPANY the engine will update it accordingly on all USER rows referencing this COMPANY (but no triggers activated on USER table, warning). The engine will track the changes for you, it's good. ON UPDATE SET NULL: if you update a company_id in a row of table COMPANY the engine will set related USERs company_id to NULL (should be available in USER company_id field). I cannot see any interesting thing to do with that on an update, but I may be wrong. And now on the ON DELETE side: Page 71 of 111

72 ON DELETE RESTRICT: the default: if you try to delete a company_id Id in table COMPANY the engine will reject the operation if one USER at least links on this company, can save your life. ON DELETE NO ACTION: same as RESTRICT ON DELETE CASCADE: dangerous: if you delete a company row in table COMPANY the engine will delete as well the related USERs. This is dangerous but can be used to make automatic cleanups on secondary tables (so it can be something you want, but quite certainly not for a COMPANY<->USER example) ON DELETE SET NULL: * handful*: if you delete a COMPANY row the related USERs will automatically have the relationship to NULL. If Null is your value for users with no company this can be a good behavior, for example maybe you need to keep the users in your application, as authors of some content, but removing the company is not a problem for you. usually my default is: ON DELETE RESTRICT ON UPDATE CASCADE with some ON DELETE CASCADE for track tables (logs--not all logs--, things like that) and ON DELETE SET NULL when the master table is a 'simple attribute' for the table containing the foreign key, like a JOB table for the USER table. */ Page 72 of 111

73 ALTER TABLE `lab1`.`test1` DROP FOREIGN KEY `fk_test1`; ALTER TABLE `lab1`.`test1` ADD CONSTRAINT `fk_test1` FOREIGN KEY (`testid`) REFERENCES `lab1`.`test` (`testid`) ON DELETE CASCADE ON UPDATE CASCADE; /* ALTER TABLE `lab1`.`test1` DROP FOREIGN KEY `fk_test1`; ALTER TABLE `lab1`.`test1` ADD CONSTRAINT `fk_test1` FOREIGN KEY (`testid`) REFERENCES `lab1`.`test`(`testid`) ON DELETE RESTRICT ON UPDATE CASCADE; */ ALTER TABLE `LAB1`.`TEST` CHANGE `testname` `test_name` VARCHAR (20); -- To change the data type and Name of a column in a table, use the following syntax `backtick`) ALTER TABLE `LAB1`.`TEST` CHANGE `test_name` `testname` varchar(20); -- To change the data type and Name of a column in a table, use the following syntax /* FOEREIGN Keys can have Null Values */ Page 73 of 111

74 INSERT INTO `LAB1`.`TEST` (testid, testname, testmarks) VALUES (1,'Quiz 01',7.5); -- The INSERT INTO statement is used to insert new records in specific columns in a table INSERT INTO `LAB1`.`TEST` (testid, testname) VALUES (2, 'Quiz 02'); -- It is also possible to only insert data in specific columns. INSERT INTO `LAB1`.`TEST1` (test1id, test1name) VALUES (1,'Quiz 01'), (2,'Quiz 02'); -- Inserting Multiple records into a 2nd table VIA Single Query -- select * from `lab1`.`test1` UPDATE `lab1`.`test` SET `test1id` = '1' WHERE `test`.`testid` = 1; -- Updating and relating Primary and Foreign Key s in a table via query UPDATE `lab1`.`test1` SET `testid` = '1' WHERE `test1`.`test1id` = 1; -- Updating and relating Primary and Foreign Key s in second table via query Page 74 of 111

75 SELECT * FROM `lab1`.`test` ORDER BY `test`.`testid` ASC; -- To show the output of all record in Ascending Order SELECT * FROM `lab1`.`test` ORDER BY `test`.`testid` DESC; -- To show the output of all record in Descending Order SELECT testid FROM `lab1`.`test` ORDER BY `test`.`testid` ASC; -- To show the output of one column in Ascending Order SELECT testid FROM `lab1`.`test` ORDER BY `test`.`testid` DESC; -- To show the output of one column in Descending Order SELECT * FROM `lab1`.`test` WHERE `test`.`testid` < 3 AND `test`.`testname` = 'Quiz 01'; /*To show the output using WHERE clause and operator s */ SELECT * FROM `lab1`.`test` WHERE `test`.`testid` <= 3 AND `test`.`testname` > 'Quiz 01'; /*To show the output using WHERE clause and operator s */ Page 75 of 111

76 select * from `lab1`.`test` order by `test`.`testid` limit 2; -- To limit the output of a record to output of: 1 and 2 select * from `lab1`.`test` order by `test`.`testid` limit 1 offset 1; -- To limit only output of 2 using offset select `testid` AS `Id` FROM `lab1`.`test` ; -- To use the ALIAS to change the table name temporary select `testid` AS `Id` FROM `lab1`.`test` order by `Id` desc ; -- To use the ALIAS to change the table name temporary and show output in Descending order select COUNT(*) from `lab1`.`test`; -- To use the COUNT(*) FUNCTION that will return the number of records in a table select COUNT(testMarks) from `lab1`.`test`; -- To use the COUNT(column_name) FUNCTION that will return the number of records in a table from a specific selected column Page 76 of 111

77 /* TRUNCATE TABLE `LAB1`.`TEST`; What if we only want to delete the data inside the table, and not the table itself. BUT it will generate an error because table are in primary to foreign relationship */ ALTER TABLE `lab1`.`test` DROP FOREIGN KEY `fk_test`; -- To drop a foreign key in second table, use the following syntax via Query ALTER TABLE `lab1`.`test1` DROP FOREIGN KEY `fk_test1`; -- To drop a foreign key in second table, use the following syntax via Query TRUNCATE TABLE `LAB1`.`TEST`; -- What if we only want to delete the data inside the table, and not the table itself TRUNCATE TABLE `LAB1`.`TEST1`; -- What if we only want to delete the data inside the table, and not the table itself Page 77 of 111

78 ALTER TABLE `LAB1`.`TEST` /* To delete a column in a table having primary key assigned but no relationship via foreign key, use the following syntax (notice that some database systems don't allow deleting a column) {this is for Multi Line Comments} */ DROP COLUMN `testid`; ALTER TABLE `LAB1`.`TEST` /* To delete a column in a table having primary key assigned but no relationship via foreign key, use the following syntax (notice that some database systems don't allow deleting a column) {this is for Multi Line Comments} */ DROP COLUMN `test1id`; ALTER TABLE `LAB1`.`TEST1` /* To delete multiple column in a table having primary key assigned but no relationship via foreign key, use the following Efficient syntax */ DROP COLUMN `testid`, DROP COLUMN `test1id`; ALTER TABLE `Lab1`.`TEST` MODIFY COLUMN `testname` varchar(30); -- To change Only the data type of a column in a table, use the following syntax Page 78 of 111

79 INSERT INTO `LAB1`.`TEST` VALUES ('Quiz 01',9.5); INSERT INTO `LAB1`.`TEST` VALUES ('Quiz 02',10); SELECT * FROM `LAB1`.`TEST` WHERE `testmarks` = '9.5'; -- It is also possible to select a specific data from a specific colum_name or label_name. DELETE FROM `LAB1`.`TEST` WHERE `testmarks`=10; -- It is also possible to delete a data from a specific ROW. DROP table if exists `lab1`.`test1`; -- To delete a Table in a Database CREATE table IF NOT EXISTS `lab1`.`test` /* Using Qualifier Character to quickly select a database and a table via Code using Console.*/ ( testid int(200) ); Page 79 of 111

80 DROP table if exists `lab1`.`test1`, `lab1`.`test`; -- To delete multiple tables in a Database via One Query DROP database if exists lab1; -- To delete a Database Page 80 of 111

81 /* Data Types in MySQL: - Date and Time Types: The MySQL date and time datatypes are: DATE - A date in YYYY-MM-DD format, between and For example, December 30th, 1973 would be stored as DATETIME - A date and time combination in YYYY-MM-DD HH:MM:SS format, between :00:00 and :59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be stored as :30:00. TIMESTAMP - A timestamp between midnight, January 1, 1970 and sometime in This looks like the previous DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on December 30th, 1973 would be stored as ( YYYYMMDDHHMMSS ). TIME - Stores the time in HH:MM:SS format. YEAR(M) - Stores a year in 2-digit or 4-digit format. If the length is specified as 2 (for example YEAR(2)), YEAR can be 1970 to 2069 (70 to 69). If the length is specified as 4, YEAR can be 1901 to The default length is 4. Numeric Data Types: MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to MySQL from a different database system, these definitions will look familiar to Page 81 of 111

82 you. The following list shows the common numeric data types and their descriptions: INT - A normal-sized integer that can be signed or unsigned. If signed, the allowable range is from to If unsigned, the allowable range is from 0 to You can specify a width of up to 11 digits. TINYINT - A very small integer that can be signed or unsigned. If signed, the allowable range is from -128 to 127. If unsigned, the allowable range is from 0 to 255. You can specify a width of up to 4 digits. SMALLINT - A small integer that can be signed or unsigned. If signed, the allowable range is from to If unsigned, the allowable range is from 0 to You can specify a width of up to 5 digits. MEDIUMINT - A medium-sized integer that can be signed or unsigned. If signed, the allowable range is from to If unsigned, the allowable range is from 0 to You can specify a width of up to 9 digits. BIGINT - A large integer that can be signed or unsigned. If signed, the allowable range is from to If unsigned, the allowable range is from 0 to You can specify a width of up to 20 digits. FLOAT(M,D) - A floating-point number that cannot be unsigned. You can define the display length (M) and the number of decimals (D). This is not required and will default to 10,2, where 2 is the number of decimals and 10 is the total number of digits (including decimals). Decimal precision can go to 24 places for a FLOAT. DOUBLE(M,D) - A double precision floating-point number that cannot be unsigned. You can define the display length (M) and the number of decimals (D). This is not required and will default to 16,4, where 4 is the number of Page 82 of 111

83 decimals. Decimal precision can go to 53 places for a DOUBLE. REAL is a synonym for DOUBLE. DECIMAL(M,D) - An unpacked floating-point number that cannot be unsigned. In unpacked decimals, each decimal corresponds to one byte. Defining the display length (M) and the number of decimals (D) is required. NUMERIC is a synonym for DECIMAL. String Types: Although numeric and date types are fun, most data you'll store will be in string format. This list describes the common string datatypes in MySQL. CHAR(M) - A fixed-length string between 1 and 255 characters in length (for example CHAR(5)), right-padded with spaces to the specified length when stored. Defining a length is not required, but the default is 1. VARCHAR(M) - A variable-length string between 1 and 255 characters in length; for example VARCHAR(25). You must define a length when creating a VARCHAR field. BLOB or TEXT - A field with a maximum length of characters. BLOBs are "Binary Large Objects" and are used to store large amounts of binary data, such as images or other types of files. Fields defined as TEXT also hold large amounts of data; the difference between the two is that sorts and comparisons on stored data are case sensitive on BLOBs and are not case sensitive in TEXT fields. You do not specify a length with BLOB or TEXT. TINYBLOB or TINYTEXT - A BLOB or TEXT column with a maximum length of 255 characters. You do not specify a length with TINYBLOB or TINYTEXT. Page 83 of 111

84 */ MEDIUMBLOB or MEDIUMTEXT - A BLOB or TEXT column with a maximum length of characters. You do not specify a length with MEDIUMBLOB or MEDIUMTEXT. LONGBLOB or LONGTEXT - A BLOB or TEXT column with a maximum length of characters. You do not specify a length with LONGBLOB or LONGTEXT. ENUM - An enumeration, which is a fancy term for list. When defining an ENUM, you are creating a list of items from which the value must be selected (or it can be NULL). For example, if you wanted your field to contain "A" or "B" or "C", you would define your ENUM as ENUM ('A', 'B', 'C') and only those values (or NULL) could ever populate that field. /* We have three fields as given below, What data type s we will choose and why? studentid INT studentfirstname VARCHAR Page 84 of 111

85 studentaddress VARCHAR If you look at the list of field types, there is an INT but no Number; and there are different Text Types to choose from. We can use INT (meaning integer) for the numbers, but again, there are a few Integer Types to choose from. And that's leaving out things like float and double. Here's given the difference between them: Integer Values TINYINT Signed: -128 to 127. Unsigned: 0 to 255 SMALLINT Signed: to Unsigned: 0 to MEDIUMINT Signed: to Unsigned: 0 to INT Signed: to Unsigned: 0 to Page 85 of 111

86 BIGINT Signed: Unsigned: 0 to The signed and unsigned are for minus and non-minus values. So, if you need to store negative values, you need to be aware of the signed ranges. If you were using a TINYINT value, for example, you can go from minus 128 to positive 127. If you didn't need the minus value, you can go from 0 to positive 255. For our address book, we have an ID field. We're using this just to identify a record (row). Each record will be unique, so it will need a different number for each. We can set it to one of the INT values. But which one? If we set ID to TINYINT, then you'd run in to problem if you tried to store more than 255 records. If you used SMALLINT, you'd have problems if you tried to store the details of friend number IF you have more than 65 and half thousand friends, then you need a different INT type. We'll assume that you don't, so we'll use SMALLINT All Integer Types cannot follow the specified range; If range is assigned in MySQL. So, Choose the One that is accurate as per your requirement against your preliminary study of field s Fields with any of the above Integer type can be made Primary Key. Page 86 of 111

87 Text Types The length for the text types can be quite confusing. The MySQL manual says this about the various lengths that each text type can hold: TINYTEXT L+1 byte, where L < 2^8 TEXT L+2 bytes, where L < 2^16 MEDIUMTEXT L+3 bytes, where L < 2^24 LONGTEXT L+4 bytes, where L < 2^32 This in not terribly helpful for beginners! So, what does it mean. Well, the L + 1 part means, "The length of the string, plus 1 byte to store the value." The translated values for each are approximately: TINYTEXT 256 bytes TEXT 64 KiloBytes MEDIUMTEXT 16 MegaBytes LONGTEXT 4 GigaBytes Text cannot follow the specified range; If range is assigned in MySQL. Fields with Text data type cannot be made Primary Key s. To confuse the issue even more, you can also use CHAR and VARCHAR to store your text. These are quite useful, if you know how many characters you want to store. For example, for a UK postcode you don't need more than 9 characters, and one of those will be a blank space. So, there's no sense in setting a postcode field to hold 4 gigabytes! Instead, use CHAR or VARCHAR. Page 87 of 111

88 CHAR You specify how many characters you want the field to hold. The maximum value is 255. For example: CHAR (10) This field can then hold a maximum of ten characters. But if you only use 4 of them, the rest of the 10 characters will be blank spaces. The blank spaces get added to the right of your text: "TEXT " "TENLETTERS" But, if range not specified than it will show only one CHARACTER in the output. Fields with CHAR data types can be set as Primary Keys with or without specifying range. Page 88 of 111

89 VARCHAR Like CHAR, but the rest of the characters are not padded with blank spaces. The maximum value before MySQL was 255. After this it's jumped to 65, 535. With VARCHAR, there is also an extra byte that records how long your text is. But, if range not specified than MySQL creates a logical error. Fields with VARCHAR data types can be set Primary Keys but range must be assigned. UNIQUE The UNIQUE constraint in MySQL does not allow to insert a duplicate value in a column. The UNIQUE constraint maintains the uniqueness of a column in a table. More than one UNIQUE column can be used in a table. Null Constraint This is an important field in database terminology. It essentially means, "Should the field contain anything?" If you set a field to NOT NULL, then you can't leave it blank when you come to adding records to your database. Otherwise you'll get errors. Page 89 of 111

90 Extra (earlier versions of phpmyadmin) This is where you can set an auto increment value. This means adding one to the previous record number. This is ideal for us, as we have an ID field. Then we don't have to worry about this field. MySQL will take care of updating it for us. */ Page 90 of 111

91 -- Implementation of Data Types via Code using Console: - drop database if exists `lab`; create database if not exists `lab`; /* drop table if exists `lab`.`std`; create table if not exists `lab`.`std` ( stdname varchar not null primary key ); insert into `lab`.`std` values ('Nouman Farooq'), ('Arslan Farooq'); Page 91 of 111

92 select * from `lab`.`std`; */ /* drop table if exists `lab`.`std1`; create table if not exists `lab`.`std1` ( stdname varchar (7) not null primary key ); insert into `lab`.`std1` values ('Nouman Farooq'), ('Arslan Farooq'); select * from `lab`.`std1`; */ Page 92 of 111

93 /* drop table if exists `lab`.`std2`; create table if not exists `lab`.`std2` ( stdname char not null primary key ); insert into `lab`.`std2` values ('Nouman Farooq'), ('Arslan Farooq'); select * from `lab`.`std2`; */ Page 93 of 111

94 /* drop table if exists `lab`.`std3`; create table if not exists `lab`.`std3` ( stdname char (7) not null primary key ); insert into `lab`.`std3` values ('Nouman Farooq'), ('Arslan Farooq'); select * from `lab`.`std3`; */ Page 94 of 111

95 /* drop table if exists `lab`.`std4`; create table if not exists `lab`.`std4` ( stdname text not null primary key ); insert into `lab`.`std4` values ('Nouman Farooq'), ('Arslan Farooq'); select * from `lab`.`std4`; */ /* drop table if exists `lab`.`std5`; Page 95 of 111

96 create table if not exists `lab`.`std5` ( stdname text(6) not null primary key ); insert into `lab`.`std4` values ('Nouman Farooq'), ('Arslan Farooq'); select * from `lab`.`std5`; */ /* drop table if exists `lab`.`std6`; create table if not exists `lab`.`std6` ( Page 96 of 111

97 ); stdname char not null primary key insert into `lab`.`std6` values ('Nouman Farooq'), ('Arslan Farooq'); UPDATE `lab`.`std6` SET stdname = 'Muhammad Farooq Khan' where stdname = 'Arslan Farooq'; select * from `lab`.`std6`; */ Page 97 of 111

98 Page 98 of 111

99 Page 99 of 111

Advance SQL: SQL Performance Tuning. SQL Views

Advance SQL: SQL Performance Tuning. SQL Views Advance SQL: SQL Performance Tuning SQL Views A view is nothing more than a SQL statement that is stored in the database with an associated name. A view is actually a composition of a table in the form

More information

Jarek Szlichta

Jarek Szlichta Jarek Szlichta http://data.science.uoit.ca/ SQL is a standard language for accessing and manipulating databases What is SQL? SQL stands for Structured Query Language SQL lets you gain access and control

More information

SQL is a standard language for accessing and manipulating databases.

SQL is a standard language for accessing and manipulating databases. Introduction to SQL SQL is a standard language for accessing and manipulating databases. What is SQL? SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL is an ANSI

More information

SQL Joins and SQL Views

SQL Joins and SQL Views SQL Joins and SQL Views There are different types of joins available in SQL: INNER JOIN: returns rows when there is a match in both tables. LEFT JOIN: returns all rows from the left table, even if there

More information

MySQL. Prof.Sushila Aghav

MySQL. Prof.Sushila Aghav MySQL Prof.Sushila Aghav Introduction SQL is a standard language for storing, manipulating and retrieving data in databases. SQL is a part of many relational database management systems like: MySQL, SQL

More information

Introduction to SQL. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

Introduction to SQL. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011 Introduction to SQL IT 5101 Introduction to Database Systems J.G. Zheng Fall 2011 Overview Using Structured Query Language (SQL) to get the data you want from relational databases Learning basic syntax

More information

Relational Database Language

Relational Database Language DATA BASE MANAGEMENT SYSTEMS Unit IV Relational Database Language: Data definition in SQL, Queries in SQL, Insert, Delete and Update Statements in SQL, Views in SQL, Specifying General Constraints as Assertions,

More information

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel 1 In this chapter, you will learn: The basic commands

More information

Data about data is database Select correct option: True False Partially True None of the Above

Data about data is database Select correct option: True False Partially True None of the Above Within a table, each primary key value. is a minimal super key is always the first field in each table must be numeric must be unique Foreign Key is A field in a table that matches a key field in another

More information

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

Advance Database Systems. Joining Concepts in Advanced SQL Lecture# 4 Advance Database Systems Joining Concepts in Advanced SQL Lecture# 4 Lecture 4: Joining Concepts in Advanced SQL Join Cross Join Inner Join Outer Join 3 Join 4 Join A SQL join clause combines records from

More information

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management Tenth Edition Chapter 7 Introduction to Structured Query Language (SQL) Objectives In this chapter, students will learn: The basic commands and

More information

CSC Web Programming. Introduction to SQL

CSC Web Programming. Introduction to SQL CSC 242 - Web Programming Introduction to SQL SQL Statements Data Definition Language CREATE ALTER DROP Data Manipulation Language INSERT UPDATE DELETE Data Query Language SELECT SQL statements end with

More information

Oracle Database 10g: Introduction to SQL

Oracle Database 10g: Introduction to SQL ORACLE UNIVERSITY CONTACT US: 00 9714 390 9000 Oracle Database 10g: Introduction to SQL Duration: 5 Days What you will learn This course offers students an introduction to Oracle Database 10g database

More information

Exam code: Exam name: Database Fundamentals. Version 16.0

Exam code: Exam name: Database Fundamentals. Version 16.0 98-364 Number: 98-364 Passing Score: 800 Time Limit: 120 min File Version: 16.0 Exam code: 98-364 Exam name: Database Fundamentals Version 16.0 98-364 QUESTION 1 You have a table that contains the following

More information

Chapter 1 SQL and Data

Chapter 1 SQL and Data Chapter 1 SQL and Data What is SQL? Structured Query Language An industry-standard language used to access & manipulate data stored in a relational database E. F. Codd, 1970 s IBM 2 What is Oracle? A relational

More information

normalization are being violated o Apply the rule of Third Normal Form to resolve a violation in the model

normalization are being violated o Apply the rule of Third Normal Form to resolve a violation in the model Database Design Section1 - Introduction 1-1 Introduction to the Oracle Academy o Give examples of jobs, salaries, and opportunities that are possible by participating in the Academy. o Explain how your

More information

T-SQL Training: T-SQL for SQL Server for Developers

T-SQL Training: T-SQL for SQL Server for Developers Duration: 3 days T-SQL Training Overview T-SQL for SQL Server for Developers training teaches developers all the Transact-SQL skills they need to develop queries and views, and manipulate data in a SQL

More information

L e a r n S q l select where

L e a r n S q l select where L e a r n S q l The select statement is used to query the database and retrieve selected data that match the criteria that you specify. Here is the format of a simple select statement: select "column1"

More information

Chapter-14 SQL COMMANDS

Chapter-14 SQL COMMANDS Chapter-14 SQL COMMANDS What is SQL? Structured Query Language and it helps to make practice on SQL commands which provides immediate results. SQL is Structured Query Language, which is a computer language

More information

EE221 Databases Practicals Manual

EE221 Databases Practicals Manual EE221 Databases Practicals Manual Lab 1 An Introduction to SQL Lab 2 Database Creation and Querying using SQL Assignment Data Analysis, Database Design, Implementation and Relation Normalisation School

More information

INTRODUCTION TO MYSQL MySQL : It is an Open Source RDBMS Software that uses Structured Query Language. It is available free of cost. Key Features of MySQL : MySQL Data Types: 1. High Speed. 2. Ease of

More information

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved. Database Foundations 6-4 Roadmap You are here Introduction to Oracle Application Express Structured Query Language (SQL) Data Definition Language (DDL) Data Manipulation Language (DML) Transaction Control

More information

Lecture 07. Spring 2018 Borough of Manhattan Community College

Lecture 07. Spring 2018 Borough of Manhattan Community College Lecture 07 Spring 2018 Borough of Manhattan Community College 1 SQL Identifiers SQL identifiers are used to identify objects in the database, such as table names, view names, and columns. The ISO standard

More information

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables INDEX Exercise No Title 1 Basic SQL Statements 2 Restricting and Sorting Data 3 Single Row Functions 4 Displaying data from multiple tables 5 Creating and Managing Tables 6 Including Constraints 7 Manipulating

More information

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1 SQL Fundamentals Chapter 3 Class 03: SQL Fundamentals 1 Class 03: SQL Fundamentals 2 SQL SQL (Structured Query Language): A language that is used in relational databases to build and query tables. Earlier

More information

SQL functions fit into two broad categories: Data definition language Data manipulation language

SQL functions fit into two broad categories: Data definition language Data manipulation language Database Principles: Fundamentals of Design, Implementation, and Management Tenth Edition Chapter 7 Beginning Structured Query Language (SQL) MDM NUR RAZIA BINTI MOHD SURADI 019-3932846 razia@unisel.edu.my

More information

SQL Interview Questions

SQL Interview Questions SQL Interview Questions SQL stands for Structured Query Language. It is used as a programming language for querying Relational Database Management Systems. In this tutorial, we shall go through the basic

More information

Data Base Lab. The Microsoft SQL Server Management Studio Part-3- By :Eng.Alaa I.Haniy.

Data Base Lab. The Microsoft SQL Server Management Studio Part-3- By :Eng.Alaa I.Haniy. Data Base Lab Islamic University Gaza Engineering Faculty Computer Department Lab -5- The Microsoft SQL Server Management Studio Part-3- By :Eng.Alaa I.Haniy. SQL Constraints Constraints are used to limit

More information

SQL. Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior

SQL. Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior SQL Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior 1 DDL 2 DATA TYPES All columns must have a data type. The most common data types in SQL are: Alphanumeric: Fixed length:

More information

Oracle Syllabus Course code-r10605 SQL

Oracle Syllabus Course code-r10605 SQL Oracle Syllabus Course code-r10605 SQL Writing Basic SQL SELECT Statements Basic SELECT Statement Selecting All Columns Selecting Specific Columns Writing SQL Statements Column Heading Defaults Arithmetic

More information

Unit 1 - Chapter 4,5

Unit 1 - Chapter 4,5 Unit 1 - Chapter 4,5 CREATE DATABASE DatabaseName; SHOW DATABASES; USE DatabaseName; DROP DATABASE DatabaseName; CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype,... columnn

More information

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

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No. Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No. # 5 Structured Query Language Hello and greetings. In the ongoing

More information

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement GIFT Department of Computing Science [Spring 2013] CS-217: Database Systems Lab-2 Manual Data Selection and Filtering using the SELECT Statement V1.0 4/12/2016 Introduction to Lab-2 This lab reinforces

More information

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 304 Introduction to Database Systems SQL DDL Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca SQL Overview Structured Query Language or SQL is the standard query language

More information

SQL stands for Structured Query Language. SQL lets you access and manipulate databases

SQL stands for Structured Query Language. SQL lets you access and manipulate databases CMPSC 117: WEB DEVELOPMENT SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL is an ANSI (American National Standards Institute) standard 1 SQL can execute queries

More information

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data 1 Writing Basic SQL SELECT Statements Objectives 1-2 Capabilities of SQL SELECT Statements 1-3 Basic SELECT Statement 1-4 Selecting All Columns 1-5 Selecting Specific Columns 1-6 Writing SQL Statements

More information

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries

More information

MySQL Introduction. By Prof. B.A.Khivsara

MySQL Introduction. By Prof. B.A.Khivsara MySQL Introduction By Prof. B.A.Khivsara Note: The material to prepare this presentation has been taken from internet and are generated only for students reference and not for commercial use. Outline Design

More information

Oracle Database 11g: SQL and PL/SQL Fundamentals

Oracle Database 11g: SQL and PL/SQL Fundamentals Oracle University Contact Us: +33 (0) 1 57 60 20 81 Oracle Database 11g: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn In this course, students learn the fundamentals of SQL and PL/SQL

More information

3ISY402 DATABASE SYSTEMS

3ISY402 DATABASE SYSTEMS 3ISY402 DATABASE SYSTEMS - SQL: Data Definition 1 Leena Gulabivala Material from essential text: T CONNOLLY & C BEGG. Database Systems A Practical Approach to Design, Implementation and Management, 4th

More information

CHAPTER4 CONSTRAINTS

CHAPTER4 CONSTRAINTS CHAPTER4 CONSTRAINTS LEARNING OBJECTIVES After completing this chapter, you should be able to do the following: Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN KEY,

More information

8) A top-to-bottom relationship among the items in a database is established by a

8) A top-to-bottom relationship among the items in a database is established by a MULTIPLE CHOICE QUESTIONS IN DBMS (unit-1 to unit-4) 1) ER model is used in phase a) conceptual database b) schema refinement c) physical refinement d) applications and security 2) The ER model is relevant

More information

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement Chapter 4 Basic SQL Basic SQL SQL language Considered one of the major reasons for the commercial success of relational databases SQL Structured Query Language Statements for data definitions, queries,

More information

MySQL by Examples for Beginners

MySQL by Examples for Beginners yet another insignificant programming notes... HOME MySQL by Examples for Beginners Read "How to Install MySQL and Get Started" on how to install, customize, and get started with MySQL. 1. Summary of MySQL

More information

Course Outline and Objectives: Database Programming with SQL

Course Outline and Objectives: Database Programming with SQL Introduction to Computer Science and Business Course Outline and Objectives: Database Programming with SQL This is the second portion of the Database Design and Programming with SQL course. In this portion,

More information

SQL OVERVIEW. CS121: Relational Databases Fall 2017 Lecture 4

SQL OVERVIEW. CS121: Relational Databases Fall 2017 Lecture 4 SQL OVERVIEW CS121: Relational Databases Fall 2017 Lecture 4 SQL 2 SQL = Structured Query Language Original language was SEQUEL IBM s System R project (early 1970 s) Structured English Query Language Caught

More information

CSCU9Q5 Introduction to MySQL. Data Definition & Manipulation (Over ~two Lectures)

CSCU9Q5 Introduction to MySQL. Data Definition & Manipulation (Over ~two Lectures) CSCU9Q5 Introduction to MySQL Data Definition & Manipulation (Over ~two Lectures) 1 Contents Introduction to MySQL Create a table Specify keys and relations Empty and Drop tables 2 Introduction SQL is

More information

Mahathma Gandhi University

Mahathma Gandhi University Mahathma Gandhi University BSc Computer science III Semester BCS 303 OBJECTIVE TYPE QUESTIONS Choose the correct or best alternative in the following: Q.1 In the relational modes, cardinality is termed

More information

Introduction to Computer Science and Business

Introduction to Computer Science and Business Introduction to Computer Science and Business This is the second portion of the Database Design and Programming with SQL course. In this portion, students implement their database design by creating a

More information

1) Introduction to SQL

1) Introduction to SQL 1) Introduction to SQL a) Database language enables users to: i) Create the database and relation structure; ii) Perform insertion, modification and deletion of data from the relationship; and iii) Perform

More information

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

Data Modelling and Databases. Exercise Session 7: Integrity Constraints Data Modelling and Databases Exercise Session 7: Integrity Constraints 1 Database Design Textual Description Complete Design ER Diagram Relational Schema Conceptual Modeling Logical Modeling Physical Modeling

More information

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210 SQL: Concepts Todd Bacastow IST 210: Organization of Data 2/17/2004 1 Design questions How many entities are there? What are the major entities? What are the attributes of each entity? Is there a unique

More information

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13 CS121 MIDTERM REVIEW CS121: Relational Databases Fall 2017 Lecture 13 2 Before We Start Midterm Overview 3 6 hours, multiple sittings Open book, open notes, open lecture slides No collaboration Possible

More information

CHAPTER: 4 ADVANCE SQL: SQL PERFORMANCE TUNING (12 Marks)

CHAPTER: 4 ADVANCE SQL: SQL PERFORMANCE TUNING (12 Marks) (12 Marks) 4.1 VIEW View: Views are virtual relations mainly used for security purpose, and can be provided on request by a particular user. A view can contain all rows of a table or select rows from a

More information

Lab # 4. Data Definition Language (DDL)

Lab # 4. Data Definition Language (DDL) Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4113: Lab # 4 Data Definition Language (DDL) Eng. Haneen El-Masry November, 2014 2 Objective To be familiar with

More information

15CSL58: DATABASE MANAGEMENT LABORATORY

15CSL58: DATABASE MANAGEMENT LABORATORY 15CSL58: DATABASE MANAGEMENT LABORATORY Subject Code: 15CSL58 I.A. Marks: 20 Hours/Week: L(1)+P(2) Exam Hours: 03 Total Hours: 40 Exam Marks: 80 Course objectives: This course will enable students to Foundation

More information

Microsoft MOS- Using Microsoft Office Access Download Full Version :

Microsoft MOS- Using Microsoft Office Access Download Full Version : Microsoft 77-605 MOS- Using Microsoft Office Access 2007 Download Full Version : http://killexams.com/pass4sure/exam-detail/77-605 QUESTION: 120 Peter works as a Database Designer for AccessSoft Inc. The

More information

Structured Query Language

Structured Query Language University College of Southeast Norway Structured Query Language Hans-Petter Halvorsen, 2016.01.08 The Tutorial is available Online: http://home.hit.no/~hansha/?tutorial=sql http://home.hit.no/~hansha

More information

Lecture 06. Fall 2018 Borough of Manhattan Community College

Lecture 06. Fall 2018 Borough of Manhattan Community College Lecture 06 Fall 2018 Borough of Manhattan Community College 1 Introduction to SQL Over the last few years, Structured Query Language (SQL) has become the standard relational database language. More than

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe CHAPTER 6 Basic SQL Slide 6-2 Chapter 6 Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries in SQL INSERT, DELETE, and UPDATE Statements in SQL Additional Features

More information

The SQL database language Parts of the SQL language

The SQL database language Parts of the SQL language DATABASE DESIGN I - 1DL300 Fall 2011 Introduction to SQL Elmasri/Navathe ch 4,5 Padron-McCarthy/Risch ch 7,8,9 An introductory course on database systems http://www.it.uu.se/edu/course/homepage/dbastekn/ht11

More information

Chapter 3. Introduction to relational databases and MySQL. 2010, Mike Murach & Associates, Inc. Murach's PHP and MySQL, C3

Chapter 3. Introduction to relational databases and MySQL. 2010, Mike Murach & Associates, Inc. Murach's PHP and MySQL, C3 1 Chapter 3 Introduction to relational databases and MySQL Slide 2 Objectives Applied 1. Use phpmyadmin to review the data and structure of the tables in a database, to import and run SQL scripts that

More information

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

tablename ORDER BY column ASC tablename ORDER BY column DESC sortingorder, } The WHERE and ORDER BY clauses can be combined in one } The result of a query can be sorted in ascending or descending order using the optional ORDER BY clause. The simplest form of an ORDER BY clause is SELECT columnname1, columnname2, FROM tablename ORDER

More information

COSC344 Database Theory and Applications. Lecture 6 SQL Data Manipulation Language (1)

COSC344 Database Theory and Applications. Lecture 6 SQL Data Manipulation Language (1) COSC344 Database Theory and Applications Lecture 6 SQL Data Manipulation Language (1) COSC344 Lecture 56 1 Overview Last Lecture SQL - DDL This Lecture SQL - DML INSERT DELETE (simple) UPDATE (simple)

More information

CMP-3440 Database Systems

CMP-3440 Database Systems CMP-3440 Database Systems Relational DB Languages SQL Lecture 06 zain 1 Purpose and Importance Database Language: To create the database and relation structures. To perform various operations. To handle

More information

Lab # 3 Hands-On. DML Basic SQL Statements Institute of Computer Science, University of Tartu, Estonia

Lab # 3 Hands-On. DML Basic SQL Statements Institute of Computer Science, University of Tartu, Estonia Lab # 3 Hands-On DML Basic SQL Statements Institute of Computer Science, University of Tartu, Estonia DML: Data manipulation language statements access and manipulate data in existing schema objects. These

More information

Structured Query Language (SQL)

Structured Query Language (SQL) Structured Query Language (SQL) SQL Chapters 6 & 7 (7 th edition) Chapters 4 & 5 (6 th edition) PostgreSQL on acsmysql1.acs.uwinnipeg.ca Each student has a userid and initial password acs!

More information

Oral Questions and Answers (DBMS LAB) Questions & Answers- DBMS

Oral Questions and Answers (DBMS LAB) Questions & Answers- DBMS Questions & Answers- DBMS https://career.guru99.com/top-50-database-interview-questions/ 1) Define Database. A prearranged collection of figures known as data is called database. 2) What is DBMS? Database

More information

Full file at

Full file at David Kroenke's Database Processing: Fundamentals, Design and Implementation (10 th Edition) CHAPTER TWO INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) True-False Questions 1. SQL stands for Standard

More information

SQL. Char (30) can store ram, ramji007 or 80- b

SQL. Char (30) can store ram, ramji007 or 80- b SQL In Relational database Model all the information is stored on Tables, these tables are divided into rows and columns. A collection on related tables are called DATABASE. A named table in a database

More information

Introduction. Sample Database SQL-92. Sample Data. Sample Data. Chapter 6 Introduction to Structured Query Language (SQL)

Introduction. Sample Database SQL-92. Sample Data. Sample Data. Chapter 6 Introduction to Structured Query Language (SQL) Chapter 6 Introduction to Structured Query Language (SQL) Introduction Structured Query Language (SQL) is a data sublanguage that has constructs for defining and processing a database It can be Used stand-alone

More information

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

What is SQL? Toolkit for this guide. Learning SQL Using phpmyadmin http://www.php-editors.com/articles/sql_phpmyadmin.php 1 of 8 Members Login User Name: Article: Learning SQL using phpmyadmin Password: Remember Me? register now! Main Menu PHP Tools PHP Help Request PHP

More information

CS6312 DATABASE MANAGEMENT SYSTEMS LABORATORY L T P C

CS6312 DATABASE MANAGEMENT SYSTEMS LABORATORY L T P C CS6312 DATABASE MANAGEMENT SYSTEMS LABORATORY L T P C 0 0 3 2 LIST OF EXPERIMENTS: 1. Creation of a database and writing SQL queries to retrieve information from the database. 2. Performing Insertion,

More information

THE UNIVERSITY OF AUCKLAND

THE UNIVERSITY OF AUCKLAND VERSION 1 COMPSCI 280 THE UNIVERSITY OF AUCKLAND SECOND SEMESTER, 2015 Campus: City COMPUTER SCIENCE Enterprise Software Development (Time allowed: 40 minutes) NOTE: Enter your name and student ID into

More information

SQL STRUCTURED QUERY LANGUAGE

SQL STRUCTURED QUERY LANGUAGE STRUCTURED QUERY LANGUAGE SQL Structured Query Language 4.1 Introduction Originally, SQL was called SEQUEL (for Structured English QUery Language) and implemented at IBM Research as the interface for an

More information

Basant Group of Institution

Basant Group of Institution Basant Group of Institution Visual Basic 6.0 Objective Question Q.1 In the relational modes, cardinality is termed as: (A) Number of tuples. (B) Number of attributes. (C) Number of tables. (D) Number of

More information

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

CS 327E Lecture 2. Shirley Cohen. January 27, 2016 CS 327E Lecture 2 Shirley Cohen January 27, 2016 Agenda Announcements Homework for today Reading Quiz Concept Questions Homework for next time Announcements Lecture slides and notes will be posted on the

More information

ASSIGNMENT NO 2. Objectives: To understand and demonstrate DDL statements on various SQL objects

ASSIGNMENT NO 2. Objectives: To understand and demonstrate DDL statements on various SQL objects ASSIGNMENT NO 2 Title: Design and Develop SQL DDL statements which demonstrate the use of SQL objects such as Table, View, Index, Sequence, Synonym Objectives: To understand and demonstrate DDL statements

More information

Oracle Create Table Foreign Key On Delete No

Oracle Create Table Foreign Key On Delete No Oracle Create Table Foreign Key On Delete No Action Can I create a foreign key against only part of a composite primary key? For example, if you delete a row from the ProductSubcategory table, it could

More information

Introduction to relational databases and MySQL

Introduction to relational databases and MySQL Chapter 3 Introduction to relational databases and MySQL A products table Columns 2017, Mike Murach & Associates, Inc. C3, Slide 1 2017, Mike Murach & Associates, Inc. C3, Slide 4 Objectives Applied 1.

More information

5. Single-row function

5. Single-row function 1. 2. Introduction Oracle 11g Oracle 11g Application Server Oracle database Relational and Object Relational Database Management system Oracle internet platform System Development Life cycle 3. Writing

More information

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama The Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4113: Database Lab Lab # 2 Data Definition Language (DDL) Eng. Alaa O Shama October, 2015 Objective To be familiar

More information

SQL Server and SQL Structured Query Language

SQL Server and SQL Structured Query Language SQL Server and SQL Structured Query Language Step by step Exercises Hans-Petter Halvorsen Database Systems Hans-Petter Halvorsen, M.Sc. Database Systems A Database is a structured way to store lots of

More information

Lesson 2. Data Manipulation Language

Lesson 2. Data Manipulation Language Lesson 2 Data Manipulation Language IN THIS LESSON YOU WILL LEARN To add data to the database. To remove data. To update existing data. To retrieve the information from the database that fulfil the stablished

More information

Networks and Web for Health Informatics (HINF 6220)

Networks and Web for Health Informatics (HINF 6220) Networks and Web for Health Informatics (HINF 6220) Tutorial #1 Raheleh Makki Email: niri@cs.dal.ca Tutorial Class Timings Tuesday & Thursday 4:05 5:25 PM Course Outline Database Web Programming SQL PHP

More information

CGS 3066: Spring 2017 SQL Reference

CGS 3066: Spring 2017 SQL Reference CGS 3066: Spring 2017 SQL Reference Can also be used as a study guide. Only covers topics discussed in class. This is by no means a complete guide to SQL. Database accounts are being set up for all students

More information

Lecture 8. Database vs. Files SQL (I) Introduction to SQL database management systems (DBMS)

Lecture 8. Database vs. Files SQL (I) Introduction to SQL database management systems (DBMS) Lecture 8 SQL (I) Money are kept by boxes buried in the ground in the backyard. Money are kept in the bank 1 Source: system analysis and design methods, by Jeffrey L Whitten et al., 2 McGraw-Hill/Irwin,

More information

DATABASES SQL INFOTEK SOLUTIONS TEAM

DATABASES SQL INFOTEK SOLUTIONS TEAM DATABASES SQL INFOTEK SOLUTIONS TEAM TRAINING@INFOTEK-SOLUTIONS.COM Databases 1. Introduction in databases 2. Relational databases (SQL databases) 3. Database management system (DBMS) 4. Database design

More information

You can write a command to retrieve specified columns and all rows from a table, as illustrated

You can write a command to retrieve specified columns and all rows from a table, as illustrated CHAPTER 4 S I N G L E - TA BL E QUERIES LEARNING OBJECTIVES Objectives Retrieve data from a database using SQL commands Use simple and compound conditions in queries Use the BETWEEN, LIKE, and IN operators

More information

Relational Data Structure and Concepts. Structured Query Language (Part 1) The Entity Integrity Rules. Relational Data Structure and Concepts

Relational Data Structure and Concepts. Structured Query Language (Part 1) The Entity Integrity Rules. Relational Data Structure and Concepts Relational Data Structure and Concepts Structured Query Language (Part 1) Two-dimensional tables whose attributes values are atomic. At every row-and-column position within the table, there always exists

More information

Slides by: Ms. Shree Jaswal

Slides by: Ms. Shree Jaswal Slides by: Ms. Shree Jaswal Overview of SQL, Data Definition Commands, Set operations, aggregate function, null values, Data Manipulation commands, Data Control commands, Views in SQL, Complex Retrieval

More information

Chapter # 7 Introduction to Structured Query Language (SQL) Part I

Chapter # 7 Introduction to Structured Query Language (SQL) Part I Chapter # 7 Introduction to Structured Query Language (SQL) Part I Introduction to SQL SQL functions fit into two broad categories: Data definition language Data manipulation language Basic command set

More information

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation Basic SQL Dr Fawaz Alarfaj Al Imam Mohammed Ibn Saud Islamic University ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation MIDTERM EXAM 2 Basic

More information

Data Manipulation Language (DML)

Data Manipulation Language (DML) In the name of Allah Islamic University of Gaza Faculty of Engineering Computer Engineering Department ECOM 4113 DataBase Lab Lab # 3 Data Manipulation Language (DML) El-masry 2013 Objective To be familiar

More information

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

Implementing Table Operations Using Structured Query Language (SQL) Using Multiple Operations. SQL: Structured Query Language Implementing Table Operations Using Structured Query Language (SQL) Using Multiple Operations Show Only certain columns and rows from the join of Table A with Table B The implementation of table operations

More information

CPS510 Database System Design Primitive SYSTEM STRUCTURE

CPS510 Database System Design Primitive SYSTEM STRUCTURE CPS510 Database System Design Primitive SYSTEM STRUCTURE Naïve Users Application Programmers Sophisticated Users Database Administrator DBA Users Application Interfaces Application Programs Query Data

More information

The query language for relational databases Jef De Smedt

The query language for relational databases Jef De Smedt SQL The query language for relational databases Jef De Smedt Getting to know Βeta vzw, Antwerp 1993 computer training for unemployed 2000 computer training for employees Cevora vzw/cefora asbl ( Fr 15/9

More information

Basic SQL. Basic SQL. Basic SQL

Basic SQL. Basic SQL. Basic SQL Basic SQL Dr Fawaz Alarfaj Al Imam Mohammed Ibn Saud Islamic University ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation Basic SQL Structured

More information

CMPT 354: Database System I. Lecture 3. SQL Basics

CMPT 354: Database System I. Lecture 3. SQL Basics CMPT 354: Database System I Lecture 3. SQL Basics 1 Announcements! About Piazza 97 enrolled (as of today) Posts are anonymous to classmates You should have started doing A1 Please come to office hours

More information

SQL (Structured Query Language)

SQL (Structured Query Language) Lecture Note #4 COSC4820/5820 Database Systems Department of Computer Science University of Wyoming Byunggu Yu, 02/13/2001 SQL (Structured Query Language) 1. Schema Creation/Modification: DDL (Data Definition

More information