SlideShare a Scribd company logo
DATABASE BEGINNING
Course: INFO 6210 Data Management and Database Design
Instructor: Prof. Chaiyaporn Mutsalklisana
• 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
• 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
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
 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
• 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
 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
 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
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
 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
 DELETE FROM table_name
WHERE some_column=some_value;
• Example:
 DELETE FROM Customer
WHERE CustomerID=123;
DELETE
 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
 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
• AVG() Function
• SUM() Function
• MIN() and MAX() Functions
• COUNT() Function
SUMMARY FUNCTIONS
• GREATEST() – It returns greatest value
Ex: 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
• 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
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
• 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
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…
• 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
• 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
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
• 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
• The INNER JOIN selects only those rows from both tables
where there is a match between the common column in
both tables.
INNER JOIN
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.
• SELECT column 1, column 2, column 3, etc.
FROM table1
JOIN/INNER JOIN table2
ON table1.column_name=table2.column_name;
INNER JOIN - SYNTAX
• Left outer join
• Right outer join
• Full outer join
OUTER 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
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.
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;
• 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
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.
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;
• 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
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.
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;
• 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
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.
• 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
• 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.Address
FROM Details AS D1 INNER JOIN Details AS D2
ON D1.Address = D2.Address AND
D1.StudentId < D2.StudentId;
SELF JOIN - EXAMPLE
StudentId Name Address
1 Tanmay 75 St. Alphonsus Street
2 Ashwin 75 St. Alphonsus Street
3 Shubham 22 parker street
4 Devashri 22 parker street
• 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 MyTable
UNION
SELECT anotherColumn, yetAnotherColumn, MoreColumn FROM MyOtherTable;
SELECT myColumn FROM MyTable
UNION
SELECT anotherColumn, yetAnotherColumn, MoreColumn FROM MyOtherTable;
ASHWIN AND TANMAY
Created By
Thank You !!

More Related Content

What's hot

SQL
SQLSQL
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
TechandMate
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
Nishant Munjal
 
Sql Basics | Edureka
Sql Basics | EdurekaSql Basics | Edureka
Sql Basics | Edureka
Edureka!
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
Saeid Zebardast
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
Stewart Rogers
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
Ritwik Das
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)
Ishucs
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
Hammad Rasheed
 
oracle Sql constraint
oracle  Sql constraint oracle  Sql constraint
oracle Sql constraint home
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In SqlAnurag
 
SQL
SQLSQL
DDL And DML
DDL And DMLDDL And DML
DDL And DML
pnp @in
 
MySQL and its basic commands
MySQL and its basic commandsMySQL and its basic commands
MySQL and its basic commands
Bwsrang Basumatary
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
Raveena Thakur
 
Basic SQL and History
 Basic SQL and History Basic SQL and History
Basic SQL and History
SomeshwarMoholkar
 
Getting Started with MySQL I
Getting Started with MySQL IGetting Started with MySQL I
Getting Started with MySQL I
Sankhya_Analytics
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
Sabana Maharjan
 
Difference Between Sql - MySql and Oracle
Difference Between Sql - MySql and OracleDifference Between Sql - MySql and Oracle
Difference Between Sql - MySql and Oracle
Steve Johnson
 

What's hot (20)

SQL
SQLSQL
SQL
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
Sql Basics | Edureka
Sql Basics | EdurekaSql Basics | Edureka
Sql Basics | Edureka
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
oracle Sql constraint
oracle  Sql constraint oracle  Sql constraint
oracle Sql constraint
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
SQL
SQLSQL
SQL
 
DDL And DML
DDL And DMLDDL And DML
DDL And DML
 
MySQL and its basic commands
MySQL and its basic commandsMySQL and its basic commands
MySQL and its basic commands
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
Basic SQL and History
 Basic SQL and History Basic SQL and History
Basic SQL and History
 
Getting Started with MySQL I
Getting Started with MySQL IGetting Started with MySQL I
Getting Started with MySQL I
 
SQL Constraints
SQL ConstraintsSQL Constraints
SQL Constraints
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Difference Between Sql - MySql and Oracle
Difference Between Sql - MySql and OracleDifference Between Sql - MySql and Oracle
Difference Between Sql - MySql and Oracle
 

Viewers also liked

Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)
Vidyasagar Mundroy
 
Tomasz Kopacz: Architektura i service fabric - jak budować aplikacje w paas v2
Tomasz Kopacz: Architektura i service fabric - jak budować aplikacje w paas v2Tomasz Kopacz: Architektura i service fabric - jak budować aplikacje w paas v2
Tomasz Kopacz: Architektura i service fabric - jak budować aplikacje w paas v2
AnalyticsConf
 
Dawid Gonzo Kałędowski: R jako osobisty GPS
Dawid Gonzo Kałędowski: R jako osobisty GPSDawid Gonzo Kałędowski: R jako osobisty GPS
Dawid Gonzo Kałędowski: R jako osobisty GPS
AnalyticsConf
 
Tor Hovland: Taking a swim in the big data lake
Tor Hovland: Taking a swim in the big data lakeTor Hovland: Taking a swim in the big data lake
Tor Hovland: Taking a swim in the big data lake
AnalyticsConf
 
What Is Reporting Services?
 What Is Reporting Services?  What Is Reporting Services?
What Is Reporting Services?
LearnItFirst.com
 
PowerBI - Porto.Data - 20150219
PowerBI - Porto.Data - 20150219PowerBI - Porto.Data - 20150219
PowerBI - Porto.Data - 20150219
Rui Romano
 
Denny Lee\'s Data Camp v1.0 talk on SSRS Best Practices for IT
Denny Lee\'s Data Camp v1.0 talk on SSRS Best Practices for ITDenny Lee\'s Data Camp v1.0 talk on SSRS Best Practices for IT
Denny Lee\'s Data Camp v1.0 talk on SSRS Best Practices for IT
Bala Subra
 
OpenRefine Class Tutorial
OpenRefine Class TutorialOpenRefine Class Tutorial
OpenRefine Class TutorialAshwin Dinoriya
 
Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesAshwin Dinoriya
 
Data Visualization-Ashwin
Data Visualization-AshwinData Visualization-Ashwin
Data Visualization-AshwinAshwin Dinoriya
 
Sql Server 2012 Reporting-Services is Now a SharePoint Service Application
Sql Server 2012   Reporting-Services is Now a SharePoint Service ApplicationSql Server 2012   Reporting-Services is Now a SharePoint Service Application
Sql Server 2012 Reporting-Services is Now a SharePoint Service Application
InnoTech
 
Welcome to PowerBI and Tableau
Welcome to PowerBI and TableauWelcome to PowerBI and Tableau
Welcome to PowerBI and TableauAshwin Dinoriya
 
Rafał Korszuń: Security in Design of Cloud Applications
Rafał Korszuń: Security in Design of Cloud ApplicationsRafał Korszuń: Security in Design of Cloud Applications
Rafał Korszuń: Security in Design of Cloud Applications
AnalyticsConf
 
Paweł Ciepły: PowerBI part1
Paweł Ciepły: PowerBI part1Paweł Ciepły: PowerBI part1
Paweł Ciepły: PowerBI part1
AnalyticsConf
 
SQL Server Reporting Services (SSRS) 101
 SQL Server Reporting Services (SSRS) 101 SQL Server Reporting Services (SSRS) 101
SQL Server Reporting Services (SSRS) 101
Sparkhound Inc.
 
SQL Server Reporting Services
SQL Server Reporting ServicesSQL Server Reporting Services
SQL Server Reporting ServicesAhmed Elbaz
 
Ssrs introduction session 1
Ssrs introduction session 1Ssrs introduction session 1
Ssrs introduction session 1
Muthuvel P
 

Viewers also liked (20)

Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)
 
Tomasz Kopacz: Architektura i service fabric - jak budować aplikacje w paas v2
Tomasz Kopacz: Architektura i service fabric - jak budować aplikacje w paas v2Tomasz Kopacz: Architektura i service fabric - jak budować aplikacje w paas v2
Tomasz Kopacz: Architektura i service fabric - jak budować aplikacje w paas v2
 
Dawid Gonzo Kałędowski: R jako osobisty GPS
Dawid Gonzo Kałędowski: R jako osobisty GPSDawid Gonzo Kałędowski: R jako osobisty GPS
Dawid Gonzo Kałędowski: R jako osobisty GPS
 
Final_Project
Final_ProjectFinal_Project
Final_Project
 
Tor Hovland: Taking a swim in the big data lake
Tor Hovland: Taking a swim in the big data lakeTor Hovland: Taking a swim in the big data lake
Tor Hovland: Taking a swim in the big data lake
 
Final presentation
Final presentationFinal presentation
Final presentation
 
What Is Reporting Services?
 What Is Reporting Services?  What Is Reporting Services?
What Is Reporting Services?
 
PowerBI - Porto.Data - 20150219
PowerBI - Porto.Data - 20150219PowerBI - Porto.Data - 20150219
PowerBI - Porto.Data - 20150219
 
Denny Lee\'s Data Camp v1.0 talk on SSRS Best Practices for IT
Denny Lee\'s Data Camp v1.0 talk on SSRS Best Practices for ITDenny Lee\'s Data Camp v1.0 talk on SSRS Best Practices for IT
Denny Lee\'s Data Camp v1.0 talk on SSRS Best Practices for IT
 
Banking Database
Banking DatabaseBanking Database
Banking Database
 
OpenRefine Class Tutorial
OpenRefine Class TutorialOpenRefine Class Tutorial
OpenRefine Class Tutorial
 
Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and Privileges
 
Data Visualization-Ashwin
Data Visualization-AshwinData Visualization-Ashwin
Data Visualization-Ashwin
 
Sql Server 2012 Reporting-Services is Now a SharePoint Service Application
Sql Server 2012   Reporting-Services is Now a SharePoint Service ApplicationSql Server 2012   Reporting-Services is Now a SharePoint Service Application
Sql Server 2012 Reporting-Services is Now a SharePoint Service Application
 
Welcome to PowerBI and Tableau
Welcome to PowerBI and TableauWelcome to PowerBI and Tableau
Welcome to PowerBI and Tableau
 
Rafał Korszuń: Security in Design of Cloud Applications
Rafał Korszuń: Security in Design of Cloud ApplicationsRafał Korszuń: Security in Design of Cloud Applications
Rafał Korszuń: Security in Design of Cloud Applications
 
Paweł Ciepły: PowerBI part1
Paweł Ciepły: PowerBI part1Paweł Ciepły: PowerBI part1
Paweł Ciepły: PowerBI part1
 
SQL Server Reporting Services (SSRS) 101
 SQL Server Reporting Services (SSRS) 101 SQL Server Reporting Services (SSRS) 101
SQL Server Reporting Services (SSRS) 101
 
SQL Server Reporting Services
SQL Server Reporting ServicesSQL Server Reporting Services
SQL Server Reporting Services
 
Ssrs introduction session 1
Ssrs introduction session 1Ssrs introduction session 1
Ssrs introduction session 1
 

Similar to DDL,DML,SQL Functions and Joins

Sql practise for beginners
Sql practise for beginnersSql practise for beginners
Sql practise for beginnersISsoft
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server iiIblesoft
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
Nitesh Singh
 
Oraclesql
OraclesqlOraclesql
Oraclesql
Priya Goyal
 
MY SQL
MY SQLMY SQL
MY SQL
sundar
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commandsBelle Wx
 
DBMS.pptx
DBMS.pptxDBMS.pptx
DBMS.pptx
Geetha Kannan
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
Achmad Solichin
 
Les09
Les09Les09
SQL report
SQL reportSQL report
SQL report
Ahmad Zahid
 
SQL Query
SQL QuerySQL Query
SQL Query
Imam340267
 
Sql
SqlSql
Lab
LabLab
Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01sagaroceanic11
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1sagaroceanic11
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
Swapnali Pawar
 

Similar to DDL,DML,SQL Functions and Joins (20)

Sql practise for beginners
Sql practise for beginnersSql practise for beginners
Sql practise for beginners
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
 
Query
QueryQuery
Query
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
MY SQL
MY SQLMY SQL
MY SQL
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
DBMS.pptx
DBMS.pptxDBMS.pptx
DBMS.pptx
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
 
Les09
Les09Les09
Les09
 
SQL report
SQL reportSQL report
SQL report
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
 
SQL Query
SQL QuerySQL Query
SQL Query
 
Less08 Schema
Less08 SchemaLess08 Schema
Less08 Schema
 
Sql
SqlSql
Sql
 
Lab
LabLab
Lab
 
Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
 
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
Views, Triggers, Functions, Stored Procedures,  Indexing and JoinsViews, Triggers, Functions, Stored Procedures,  Indexing and Joins
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
 

DDL,DML,SQL Functions and Joins

  • 1. DATABASE BEGINNING Course: INFO 6210 Data Management and Database Design Instructor: Prof. Chaiyaporn Mutsalklisana
  • 2. • 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
  • 3. • 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
  • 4. 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
  • 5.  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
  • 6. • 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
  • 7.  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
  • 8.  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
  • 9. 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
  • 10.  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
  • 11.  DELETE FROM table_name WHERE some_column=some_value; • Example:  DELETE FROM Customer WHERE CustomerID=123; DELETE
  • 12.  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
  • 13.  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
  • 14. • AVG() Function • SUM() Function • MIN() and MAX() Functions • COUNT() Function SUMMARY FUNCTIONS
  • 15. • GREATEST() – It returns greatest value Ex: 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
  • 16. • 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
  • 17. 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
  • 18. • 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
  • 19. 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…
  • 20. • 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
  • 21. • 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
  • 22. JOINS
  • 23. • 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
  • 24. • 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
  • 25. • The INNER JOIN selects only those rows from both tables where there is a match between the common column in both tables. INNER JOIN
  • 26. 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.
  • 27. • SELECT column 1, column 2, column 3, etc. FROM table1 JOIN/INNER JOIN table2 ON table1.column_name=table2.column_name; INNER JOIN - SYNTAX
  • 28. • Left outer join • Right outer join • Full outer join OUTER JOINS
  • 29. • 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
  • 30. 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.
  • 31. 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;
  • 32. • 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
  • 33. 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.
  • 34. 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;
  • 35. • 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
  • 36. 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.
  • 37. 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;
  • 38. • 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
  • 39. 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.
  • 40. • 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
  • 41. • 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.Address FROM Details AS D1 INNER JOIN Details AS D2 ON D1.Address = D2.Address AND D1.StudentId < D2.StudentId; SELF JOIN - EXAMPLE StudentId Name Address 1 Tanmay 75 St. Alphonsus Street 2 Ashwin 75 St. Alphonsus Street 3 Shubham 22 parker street 4 Devashri 22 parker street
  • 42. • 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 MyTable UNION SELECT anotherColumn, yetAnotherColumn, MoreColumn FROM MyOtherTable; SELECT myColumn FROM MyTable UNION SELECT anotherColumn, yetAnotherColumn, MoreColumn FROM MyOtherTable;
  • 43. ASHWIN AND TANMAY Created By Thank You !!