43
DATABASE BEGINNING Course: INFO 6210 Data Management and Database Design Instructor: Prof. Chaiyaporn Mutsalklisana

DDL,DML,SQL Functions and Joins

Embed Size (px)

Citation preview

Page 1: DDL,DML,SQL Functions and Joins

DATABASE BEGINNING

Course: INFO 6210 Data Management and Database DesignInstructor: Prof. Chaiyaporn Mutsalklisana

Page 2: DDL,DML,SQL Functions and Joins

• DDL• CREATE• USE• ALTER• DROP

• DML• INSERT• SELECT• UPDATE• DELETE

• Data Manipulating Functions – Functions in SQL Statement• Summary Functions• String and Numeric Functions• Comparison and Cast Functions • Control Flow Functions• Date/Time Functions

OVERVIEW PART - I

Page 3: DDL,DML,SQL Functions and Joins

• Joins• Inner Join• Outer Join

– Left Outer Join– Right Outer Join– Full Outer Join

• Cross Join• Self Join• Operators – Union and Union All

OVERVIEW PART - II

Page 4: DDL,DML,SQL Functions and Joins

CREATE DATABASE [IF NOT EXISTS] <database name>;

- IF NOT EXISTS checks whether database with the same name exists or not

USE <database name>;

- Defines the context for creating tables or executing any statement for that database

ALTER DATABASE <database name>

- Allows you to change CHARACTER SET and/or COLLATE of database

DROP DATABASE <database name>;

- Allows you to delete database with all tables in it

Example:

CREATE DATABASE [IF NOT EXISTS] Customer;

USE Customer;

ALTER DATABASE Customer COLLATE latin1_bin;

DROP DATABASE Customer;

DATABASE: CREATE, USE, ALTER, DROP

Page 5: DDL,DML,SQL Functions and Joins

CREATE TABLE table_name (column_name1 data_type(size),column_name2 data_type(size),column_name3 data_type(size),.... );

Example: CREATE TABLE Student (StudentID int,LastName varchar(255),FirstName varchar(255),Address varchar(255),City varchar(255),Major varchar(255) );

TABLE: CREATE

Page 6: DDL,DML,SQL Functions and Joins

• NOT NULL - A value in a column can not be NULL• UNIQUE - Each row for a column must have a unique value• PRIMARY KEY - Identifies each record uniquely. Its a combination

of a NOT NULL and UNIQUE. Ensures that a column (or combination of two or more columns) have an unique identity which helps to find a particular record in a table more easily and quickly

• FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in another table

• CHECK - Ensures that the value in a column meets a specific condition

• DEFAULT - Specifies a default value when specified none for this column

CONSTRAINTS

Page 7: DDL,DML,SQL Functions and Joins

CREATE TABLE Customer( CustomerID int, LastName varchar(255), FirstName varchar(255), SSN bigint NOT NULL, Address varchar(255), City varchar(255) DEFAULT ‘NA’, UNIQUE (SSN), CHECK (CustomerID > -1), PRIMARY KEY (CustomerID) );

DEFINING CONSTRAINTS

Page 8: DDL,DML,SQL Functions and Joins

CREATE TABLE ORDERS  (Order_ID integer,  Order_Date date,  Customer_SID integer,  Amount double,  Primary Key (Order_ID),  Foreign Key (Customer_SID) REFERENCES CUSTOMER(CustomerID));

FOREIGN KEY CONSTRAINT

Page 9: DDL,DML,SQL Functions and Joins

INSERT INTO table_name VALUES (value1,value2,value3,...),(value1,value2,value3,...),…;INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3);INSERT INTO table_name (column1, column2) VALUES (value1, value2);

Example:INSERT INTO Customer(CustomerID,LastName,FirstName,Address,City,SSN) VALUES (234,'Dinoriya','Ashwin','Longwood','NewYork',1234567890);INSERT INTO Customer VALUES (123,'Ingle','Tanmay','Cityview','Boston',9876543210);INSERT INTO Customer(CustomerID, LastName, Address, City) VALUES (345,'Cardinal','Skagen 21','Norway');

INSERT INTO

Page 10: DDL,DML,SQL Functions and Joins

UPDATE table_name SET column1=value1,column2=value2,... WHERE some_column=some_value;

Example UPDATE Customer SET FirstName=‘Ashwinkumar’, Address=‘Cityview’ WHERE CustomerID=123;

UPDATE

Page 11: DDL,DML,SQL Functions and Joins

DELETE FROM table_name WHERE some_column=some_value;

• Example: DELETE FROM Customer WHERE CustomerID=123;

DELETE

Page 12: DDL,DML,SQL Functions and Joins

SELECT column_name_1, column_name_2 FROM table_name ; SELECT * FROM table_name ;

Example: SELECT LastName, FirstName, City

FROM Customer; SELECT * FROM Customer;

SELECT

Page 13: DDL,DML,SQL Functions and Joins

DROP TABLE IF EXISTS ‘table_name’; TRUNCATE TABLE ‘table_name’;

Example: DROP TABLE IF EXISTS Customer;TRUNCATE TABLE Customer;

So, What is the difference between DROP and TRUNCATE ??

DROP & TRUNCATE TABLE

Page 14: DDL,DML,SQL Functions and Joins

• AVG() Function

• SUM() Function

• MIN() and MAX() Functions

• COUNT() Function

SUMMARY FUNCTIONS

Page 15: DDL,DML,SQL Functions and Joins

• GREATEST() – It returns greatest valueEx: SELECT GREATEST(4, 83, 0, 9, -3); 83

• LEAST() – It returns least value Ex: SELECT LEAST(4, 83, 0, 9, -3); -3

• ISNULL()- It returns a value of 1 if the expression evaluates to NULL; otherwise, the function returns a value of 0

Ex: SELECT ISNULL(1*NULL); 1

COMPARISON FUNCTIONS

Page 16: DDL,DML,SQL Functions and Joins

• CEIL() or CEILING(): SELECT CEILING(9.327); 10• FLOOR(): SELECT CEILING(9.327); 9• COT(<number>) : Calculates cotangent of number• MOD(n1,n2) : Returns the remainder derived by dividing two

numbers(n1/n2)• PI() : Returns 3.141593.• POW(<number>, <power>) and POWER(<number>, <power>):

Raises the value of one number to the power of the second number• ROUND(4.27943, 2) 4.28• TRUNCATE(4.27943, 2) 4.27• SQRT(36) 6

NUMERIC FUNCTIONS

Page 17: DDL,DML,SQL Functions and Joins

CAST(<expression> AS <type>)

Ex: SELECT CAST(20041031 AS DATE);• The conversion types available to the CAST() function are as follows:❑ BINARY❑ CHAR❑ DATE❑ DATETIME❑ SIGNED and UNSIGNED [INTEGER]❑ TIME

CONVERT(<expression>, <type>) • The CONVERT() function allows you to convert dates in the same way as the CAST()

function

CAST FUNCTIONS

Page 18: DDL,DML,SQL Functions and Joins

• IF() : IF(<expression1>, <expression2>, <expression3)

If <expression1> evaluates to true, then the function returns <expression2>; otherwise, the function returns <expression3>

• IFNULL(): IFNULL(<expression1>, <expression2>)

The function returns <expression1> if it is not NULL; otherwise, it returns <expression2>

NULLIF(): IFNULL(<expression1>, <expression2>)

The NULLIF() function returns NULL if <expression1> equals <expression2>; otherwise, it returns <expression1>

CONTROL FLOW FUNCTIONS

Page 19: DDL,DML,SQL Functions and Joins

CASE():CASE WHEN <expression> THEN <result> [{WHEN <expression> THEN <result>}...] [ELSE <result>] END The WHEN...THEN clause specifies the expression to be evaluated and the results to be returned if that

expression evaluates to true

CASE <expression> WHEN <value> THEN <result> [{WHEN <value> THEN <result>}...] [ELSE <result>] END The main difference in this version of the CASE() function is that the expression is specified after the

keyword CASE, and the WHEN...THEN clauses include the possible values that result from that expression.

CONTROL FLOW CONT’D…

Page 20: DDL,DML,SQL Functions and Joins

• CURDATE(), CURRENT_DATE(), CURTIME(), CURRENT_TIME(), CURRENT_TIMESTAMP(), NOW() : Retrieve current date and time information

• DATE(), MONTH(), MONTHNAME(), and YEAR(): Allows you to extract specific information from a date or time value.

• DATEDIFF() and TIMEDIFF() : Determines the differences between dates and times

• DAY(), DAYOFMONTH(), DAYNAME(), DAYOFWEEK(), and DAYOFYEAR() : Allows you to pull day-related values out of date or date/time values

• SECOND(), MINUTE(), HOUR(), and TIME(): Extract time parts from a time or date/time value

DATE/TIME FUNCTIONS

Page 21: DDL,DML,SQL Functions and Joins

• CHAR_LENGTH(), CHARACTER_LENGTH(): Both returns the number of characters in the specified string

• LENGTH() : It returns the length of a string, only the length is measured in bytes, rather than characters.

• CHARSET() and COLLATION() : Returns Character Set and Collation type of database

• CONCAT() and CONCAT_WS() : allow you to concatenate data. • LCASE(), LOWER(), UCASE(), and UPPER() : allow you to change

string values to upper or lowercase• LEFT(<string>, <length>) and RIGHT(<string>, <length>): The

<length> value determines how many characters are returned, starting at the left/right end of the string

• REPEAT(<string>, <count>) and REVERSE(<string>)

STRING FUNCTIONS

Page 22: DDL,DML,SQL Functions and Joins

JOINS

Page 23: DDL,DML,SQL Functions and Joins

• Joins enable you to retrieve related data from different tables and display that data in one results set.

• It combine rows from two or more tables, based on a common field between them.

JOIN

Page 24: DDL,DML,SQL Functions and Joins

• Now when we look at the data of Product table we can see Vendor and Category in the form of a foreign key i.e. a number.

• If we want to see a table with three columns namely productname, VendorName and CategoryName we will have to link the above tables. This link is called as ‘JOIN’.

• There are 6 types of Joins – Inner Join, Left Outer Join, Right Outer Join, Full Join, Self Join and Cross Join. Lets look at each of them.

JOIN

Page 25: DDL,DML,SQL Functions and Joins

• The INNER JOIN selects only those rows from both tables where there is a match between the common column in both tables.

INNER JOIN

Page 26: DDL,DML,SQL Functions and Joins

INNER JOIN - EXAMPLE

If we want to create a temporary table, just for display sake with two columns, first column being ProductName and second column being VendorName, we create a Join between the two tables on the common column which in this case is VendorID

As you can see only the columns with common VendorIDs are displayed. Since there is no product with VendorID 9,10 or 11, those Vendor Names are not displayed. This is called as inner join.

Page 27: DDL,DML,SQL Functions and Joins

• SELECT column 1, column 2, column 3, etc.

FROM table1

JOIN/INNER JOIN table2

ON  table1.column_name=table2.column_name;

INNER JOIN - SYNTAX

Page 28: DDL,DML,SQL Functions and Joins

• Left outer join• Right outer join• Full outer join

OUTER JOINS

Page 29: DDL,DML,SQL Functions and Joins

• Return all rows from the left table, and the matched rows from the right table

• The result is NULL in the right side when there is no match

• Also called as ‘left join’

LEFT OUTER JOIN

Page 30: DDL,DML,SQL Functions and Joins

LEFT OUTER JOIN - EXAMPLE

If we want to include all the vendornames irrespective of if they are present in the product table we use left outer join keeping Vendor table on the left

Thus it includes every value present in the left table and displays ‘Null” value in the other column. Thus we can understand that there is no product from the vendors like Dell, Panasonic and HP.

Page 31: DDL,DML,SQL Functions and Joins

LEFT JOIN - SYNTAX

SELECT column 1, column 2, column 3, etc.

FROM table1

LEFT JOIN/LEFT OUTER JOIN table2

ON  table1.column_name=table2.column_name;

Page 32: DDL,DML,SQL Functions and Joins

• Return all rows from the right table, and the matched rows from the left table

• The result is NULL in the right side when there is no match

• Also called as ‘right join’

RIGHT OUTER JOIN

Page 33: DDL,DML,SQL Functions and Joins

RIGHT OUTER JOIN - EXAMPLE

Right Outer Join works exactly like left outer join but in the reverse way.

In the above query we have created a right join on Vendor and product in which product table is on the right.

Since there are no such values in Product which aren’t present in Vendor, the result displayed is same as inner join result.

Page 34: DDL,DML,SQL Functions and Joins

RIGHT JOIN - SYNTAX

SELECT column 1, column 2, column 3, etc.

FROM table1

RIGHT JOIN/RIGHT OUTER JOIN table2

ON  table1.column_name=table2.column_name;

Page 35: DDL,DML,SQL Functions and Joins

• The FULL OUTER JOIN returns all rows from the left table and from the right table.

• It combines the result of both LEFT and RIGHT joins.

FULL OUTER JOIN

Page 36: DDL,DML,SQL Functions and Joins

FULL OUTER JOIN EXAMPLE

Full Join displays all rows of the foreign key column from both the tables irrespective of if that value is present in the other table.

Can you guess?

Since there is no such value of foreign key in Product table which isn’t in Vendor table, this query will give results similar to those of left join on vendor and product or right join on product and vendor.

Page 37: DDL,DML,SQL Functions and Joins

FULL OUTER JOIN - SYNTAX

SELECT column 1, column 2, column 3, etc.

FROM table1

FULL OUTER JOIN table2

ON  table1.column_name=table2.column_name;

Page 38: DDL,DML,SQL Functions and Joins

• Returns the Cartesian product of rows from tables in the join.• It will produce rows which combine each row from the first table with each

row from the second table• Within SELECT statement, use CROSS JOIN explicitly or implicitly

CROSS JOIN

Page 39: DDL,DML,SQL Functions and Joins

CROSS JOIN - EXAMPLE

This is the least used join and most basic one. It includes all rows from both the tables in the result set. The result set is the Cartesian product of both the tables, such that all the rows from one table combined with all the rows from another table.

It will contain 11* 7 = 77 rows.

Page 40: DDL,DML,SQL Functions and Joins

• A self-join occurs when a table is joined to itself rather than to another table• Self-joins are also very useful in conjunction with subqueries• When joining a table to itself, you must give the table an alias• To give a table or column an alias, you simply put the keyword AS after the

table or column name and specify what you want the table to be known as.

SELECT VendorName AS VN FROM Vendor

SELF JOIN

Page 41: DDL,DML,SQL Functions and Joins

• If you need to compare the same fields but different records, you need a self-join.• If you want to know all the students who stay at the same address

SELECT D1.StudentId, D1.Name, D1.Address, D2.StudentId,D2.Name, D2.AddressFROM Details AS D1 INNER JOIN Details AS D2ON D1.Address = D2.Address ANDD1.StudentId < D2.StudentId;

SELF JOIN - EXAMPLE

StudentId Name Address1 Tanmay 75 St. Alphonsus Street2 Ashwin 75 St. Alphonsus Street3 Shubham 22 parker street4 Devashri 22 parker street

Page 42: DDL,DML,SQL Functions and Joins

• At times, you might want to combine the results of two quite distinct queries. There may be no link between the results of each query; you just want to display them all in one results set.

• You can join the results from two or more SELECT queries into one results set by using the UNION operator.

• Each query must produce the same number of columns and columns’ data types must be the same

OPERATORS – UNION, UNION ALL

SELECT myColumn, myOtherColumn, someColumn FROM MyTableUNIONSELECT anotherColumn, yetAnotherColumn, MoreColumn FROM MyOtherTable;

SELECT myColumn FROM MyTableUNIONSELECT anotherColumn, yetAnotherColumn, MoreColumn FROM MyOtherTable;

Page 43: DDL,DML,SQL Functions and Joins

ASHWIN AND TANMAY

Created By

Thank You !!