SlideShare a Scribd company logo
1 of 131
Course code: ITI131
Course title : Database
PART: 2
Prof. Taymoor Mohamed Nazmy
Dept. of computer science, faculty of computer science, Ain Shams uni.
Ex-vice dean of post graduate studies and research Cairo, Egypt
1
Relational algebra
2
Relational algebra, SQL, and the DBMS?
parser
SQL
Relational
algebra
expression
Optimized
Relational
algebra
expression
Query optimizer
Code
generator
Query
execution
plan
Executable
code
DBMS
Introduction
• Query language is a language in which user requests information
from the database. it can be categorized as either procedural or
nonprocedural.
• In a procedural language the user instructs the system to do a
sequence of operations on database to compute the desired result.
• In nonprocedural language the user describes the desired
information without giving a specific procedure for obtaining that
information.
• The relational algebra is a procedural query language. It consists of
a set of operations that take one or two relations as input and
produces a new relation as output
5
Relational Query Languages
• Languages for describing queries on a relational
database
• Structured Query Language (SQL)
– Predominant application-level query language
– Declarative
• Relational Algebra
– Intermediate language used within DBMS
– Procedural
• To process a query, a DBMS translates SQL into a
notation similar to relational algebra.
Relational Algebra
• Relational Algebra is a procedural
language that can be used to tell
the DBMS ( Data Base Management
System) how to build a new relation from
one or more relations in the database.
6
7
Formal Relational Query Languages
Two mathematical Query Languages form the basis for
formal relational query languages:
• Relational Algebra: More operational, very useful for
representing execution plans.
• Relational Calculus: Lets users describe what they want,
rather than how to compute it. (Non-operational,
declarative.)
 Understanding Algebra & Calculus is key to
 understanding SQL, query processing!
Relational Algebra operations
9
Relational Algebra Operations
10
Example Instances
sid sname rating age
22 dustin 7 45.0
31 lubber 8 55.5
58 rusty 10 35.0
sid sname rating age
28 yuppy 9 35.0
31 lubber 8 55.5
44 guppy 5 35.0
58 rusty 10 35.0
sid bid day
22 101 10/10/96
58 103 11/12/96
R1
S1
S2
• Consider the following
instances R1, S1, S2.
Basic Relational Algebra Operations (Unary):
Selection, Projection
Selection:  <condition(s)> (<relation>)
• Picks tuples from the relation
Projection:  <attribute-list> (<relation>)
• Picks columns from the relation
12
Selection (  )
rating
S
8
2( )
sid sname rating age
28 yuppy 9 35.0
58 rusty 10 35.0
sname rating
yuppy 9
rusty 10
))2(
8
(
,
S
ratingratingsname 

• Selects rows that satisfy selection
condition.
• No duplicates in result! (Why?)
• Schema of result identical to
schema of (only) input relation.
• Result relation can be the input for
another relational algebra
operation! (Operator
composition.)
S2
sid sname rating age
28 yuppy 9 35.0
31 lubber 8 55.5
44 guppy 5 35.0
58 rusty 10 35.0
13
Projection ( )
sname rating
yuppy 9
lubber 8
guppy 5
rusty 10
sname rating
S
,
( )2
age
35.0
55.5
age S( )2
• Deletes attributes that are not in projection list.
• Schema of result contains exactly the fields in the
projection list, with the same names that they had
in the (only) input relation.
• Projection operator has to eliminate duplicates!
sid sname rating age
28 yuppy 9 35.0
31 lubber 8 55.5
44 guppy 5 35.0
58 rusty 10 35.0
S2
Relational Algebra Operations (Set):
Union, Set Difference, and intersection
Union: (<relation>) U (<relation>)
• New relation contains all tuples from both relations,
duplicate tuples eliminated.
Set Difference: R – S
• Produces a relation with tuples that are in R but NOT in S.
Intersection:
R S
• All tuples that are in both R and S
15
Union, Intersection, Set-Difference
sid sname rating age
22 dustin 7 45.0
31 lubber 8 55.5
58 rusty 10 35.0
44 guppy 5 35.0
28 yuppy 9 35.0
sid sname rating age
31 lubber 8 55.5
58 rusty 10 35.0
S S1 2
S S1 2
sid sname rating age
22 dustin 7 45.0
S S1 2
sid sname rating age
28 yuppy 9 35.0
31 lubber 8 55.5
44 guppy 5 35.0
58 rusty 10 35.0
S2
sid sname rating age
22 dustin 7 45.0
31 lubber 8 55.5
58 rusty 10 35.0
S1
Relational Algebra Operations (Set):
Cartesian Product, Intersect
Cartesian Product: R x S
• Produces a relation that is concatenation of
every tuple of R with every tuple of S
• The Above operations are the 5 fundamental
operations of relational algebra.
17
Cross-Product ()
• S1  R1 : Each row of S1 is paired with each row of R1.
• Result schema has one field per field of S1 and R1, with field
names `inherited’ if possible.
– Conflict: Both S1 and R1 have a field called sid.
(sid) sname rating age (sid) bid day
22 dustin 7 45.0 22 101 10/10/96
22 dustin 7 45.0 58 103 11/12/96
31 lubber 8 55.5 22 101 10/10/96
31 lubber 8 55.5 58 103 11/12/96
58 rusty 10 35.0 22 101 10/10/96
58 rusty 10 35.0 58 103 11/12/96
sid sname rating age
22 dustin 7 45.0
31 lubber 8 55.5
58 rusty 10 35.0
sid bid day
22 101 10/10/96
58 103 11/12/96
R1
S1
Structured Query Language
SQL
18
Introduction
• SQl designed for managing data held in a relational
database management system (RDBMS),
• Originally based upon relational algebra and tuple
relational calculus, SQL consists of a data definition
language, data manipulation language, and data control
language.
• The scope of SQL includes data insert, query, update
and delete, schema creation and modification, and data
access control.
History of SQL
• SQL: Structured Query Language, used to be called SEQEL
• SQL is based on the relational tuple calculus
• SEQUEL: It was designed by IBM Research as the interface for
an experimental relational database system called SYSTEM R.
1974.
• SQL/86: ANSI & ISO standard
• SQL/89: ANSI & ISO standard
• SQL/92 or SQL2: ANSI & ISO standard
• SQL3: in the works...
• SQL2 supported by RDMS such as:
• ORACLE, SYBASE, INFORMIX, IBM DB2, SQL SERVER,
and Open Source’s MySQL,
Extended Versions of SQL
• However most Database Management Systems (DBMS) provide non-standard
extensions to SQL that include procedural elements, the following table show some
of those extensions:
Source Common name Full name
ANSI/ISO Standard SQL/PSM SQL/Persistent Stored Modules
Interbase / Firebird PSQL Procedural SQL
IBM DB2 SQL PL
SQL Procedural Language (implements
SQL/PSM)
IBM Informix SPL Stored Procedural Language
IBM Netezza NZPLSQL[18] (based on Postgres PL/pgSQL)
Microsoft / Sybase T-SQL
Transact-SQL
Mimer SQL SQL/PSM
SQL/Persistent Stored Module (implements
SQL/PSM)
MySQL SQL/PSM
SQL/Persistent Stored Module (implements
SQL/PSM)
MonetDB SQL/PSM
SQL/Persistent Stored Module (implements
SQL/PSM)
NuoDB SSP
Starkey Stored Procedures
Oracle PL/SQL Procedural Language/SQL (based on Ada)
PostgreSQL PL/pgSQL
Procedural Language/PostgreSQL Structured
Query Language (implements SQL/PSM)
Sybase Watcom-SQL SQLAnywhere Watcom-SQL Dialect
Teradata SPL Stored Procedural Language
SAP SAP HANA SQL Script
MySQL
2/7/2020
 MySQL is the world's most popular open source database
software, with over 100 million copies of its software
downloaded or distributed throughout it's history.
 MySQL is a relational database management system (
RDBMS ) and which runs a server, providing multi-user
access to a number of databases.
 With its superior speed, reliability, and ease of use, MySQL
has become the preferred choice for IT in all sectors or
domains.
What is SQL?
• When a user wants to get some information
• from a database file, he can issue a query.
• – A query is a user–request to retrieve data or
• information with a certain condition.
• – SQL is a query language that allows user to
• specify the conditions. (instead of algorithms)
23
SQL language is divided into four types
DML (Data Manipulation Language)
• DML statements affect records in a table. These
are basic operations we perform on data such as
selecting a few records from a table, inserting new
records, deleting unnecessary records, and
updating/modifying existing records.
• DML statements include the following:
• SELECT – select records from a table
INSERT – insert new records
UPDATE – update/Modify existing records
DELETE – delete existing records
DDL (Data Definition Language)
• DDL statements are used to alter/modify a
database or table structure and schema. These
statements handle the design and storage of
database objects.
• CREATE – create a new Table, database, schema
ALTER – alter existing table, column description
DROP – delete existing objects from database
DCL (Data Control Language)
• DCL statements control the level of access that
users have on database objects.
• GRANT – allows users to read/write on
certain database objects
•
REVOKE – keeps users from read/write
permission on database objects
TCL (Transaction Control Language)
• TCL statements allow you to control and manage
transactions to maintain the integrity of data
within SQL statements.
• BEGIN Transaction – opens a transaction
COMMIT Transaction – commits a transaction
•
ROLLBACK Transaction – ROLLBACK a
transaction in case of any error
Using SQL in Your Web Site
• To build a web site that shows data from a database,
you will need:
• An RDBMS database program (i.e. MS Access, SQL
Server, MySQL)
• To use a server-side scripting language, like PHP or
ASP
• To use SQL to get the data you want to use HTML /
CSS to style the page
30
Using SQL
SQL statements can be embedded into a program (cgi or
perl script, Visual Basic, MS Access)
OR
SQL statements can be entered directly at the
command prompt of the SQL software being used
(such as mySQL)
Keep in Mind that
• SQL keywords are NOT case sensitive: select is
the same as SELECT.
• Some database systems require a semicolon at the
end of each SQL statement.
• Semicolon is the standard way to separate each
SQL statement in database systems that allow
more than one SQL statement to be executed in
the same call to the server.
SQL Statements, Operations, Clauses
SQL Statements such as :
Select
SQL Operations such as:
Join
Left Join
Right Join
Like
SQL Clauses such as:
Order By
Group By
Having
Some of The Most Important SQL Statements
• SELECT - extracts data from a database
• UPDATE - updates data in a database
• DELETE - deletes data from a database
• INSERT INTO - inserts new data into a database
• CREATE DATABASE - creates a new database
• ALTER DATABASE - modifies a database
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table
• CREATE INDEX - creates an index (search key)
• DROP INDEX - deletes an index
Learning and execute SQl online
• https://www.w3schools.com/sql/default.asp
SQL: Attributes Types (data type)
CHARACTER [(length)] or CHAR [(length)]
• The CHARACTER data type accepts character strings,
including Unicode, of a fixed length. The length of the
character string should be specified in the data type
declaration; for example, CHARACTER(n) where n represents
the desired length of the character string.
• If no length is specified during the declaration, the default
length is 1. Used to store character string value of fixed
length.
• The maximum no. of characters the data type can hold is 255
characters. It's 50% faster than VARCHAR. Any remaining
space in the field is padded with blanks.
CHARACTER [(length)] or CHAR [(length)]
• CHAR(10) or CHARACTER(10)
• Valid
• 'Race car'
• 'RACECAR'
• '24865'
• '1998-10-25'
• '1998-10-25 ' (Blank characters are truncated)
•
Invalid
24865
1998-10-25
'Date: 1998-10-25'
VARCHAR (length)
• The VARCHAR data type accepts character strings, including Unicode, of
a variable length is up to the maximum length specified in the data type
declaration.
• Examples
• VARCHAR(10)
• Valid
• 'Race car'
• 'RACECAR'
• '24865'
• '1998-10-25'
• '1998-10-25 '
Invalid
24865
1998-10-25
'Date: 1998-10-25'
BOOLEAN
• The BOOLEAN data type supports the storage of two values: TRUE or
FALSE. No parameters are required when declaring a BOOLEAN data type.
• Examples
• BOOLEAN
• Valid
• TRUE
• true
• True
• False
Invalid
1
0
Yes
No
SMALLINT
• The SMALLINT data type accepts numeric values with an implied scale of
zero. It stores any integer value between the range 2^ -15 and 2^15-1.
• SMALLINT
• Valid
• -32768
• 0
• -30.3 (digits to the right of the
• decimal point are truncated)
• 32767
Invalid
-33,000,567
1,897,536,000
INTEGER or INT
• The INTEGER data type accepts numeric values with an implied
scale of zero. It stores any integer value between the range 2^ -31
and 2^31 -1
• Examples INTEGER or INT
• Valid
• -2147483648
• -1025
• 0
• 1025.98 (digits to the right of the
• decimal point are truncated)
• 2147483647
Invalid
-1,025,234,000,367
1,025,234,000,367
DECIMAL [(p[,s])] or DEC [(p[,s])]
• The DECIMAL data type accepts numeric values, for which you may
define a precision and a scale in the data type declaration.
• The precision is an integer that indicates the number of digits that the
number will contain. The scale is an integer that indicates the number of
these digits that will represent decimal places to the right of the decimal
point.
• Examples DECIMAL(10,3)
•
• Valid
• 1234567
• 1234567.123
• -1234567
Invalid
12345678
12345678.12
12345678.123
-12345678
-12345678.12
-12345678.123
REAL
• The REAL data type accepts approximate numeric values, up to a precision of 64.
No parameters are required when declaring a REAL data type. If you attempt to
assign a value with a precision greater than 64 an error is raised.
• Examples
• REAL
• Valid
• -2345
• 0
• 1E-3
• 1.245
• 123456789012345678901234567890
Invalid
123,456,789,012,345,678,901,234,567,890,123
DATE
• The DATE data type accepts date values. No parameters are
required when declaring a DATE data type. Date values
should be specified in the form: YYYY-MM-DD. However,
PointBase will also accept single digits entries for month
and day values.
• Examples
• DATE
• Valid
• DATE '1999-01-01'
• DATE '2000-2-2'
Invalid
DATE '1999-13-1'
date '2000-2-30'
'2000-2-27'
date 2000-2-27
TIME
• The TIME data type accepts time values. No parameters are required
when declaring a TIME data type. time values should be specified in
the form: HH:MM:SS
• Examples
• TIME
• Valid
• TIME '00:00:00'
• TIME '1:00:00'
• TIME '23:59:59'
• time '23:59:59.99'
Invalid
TIME '00:62:00'
TIME '00:3:00'
TIME '23:01'
'24:01:00'
TIMESTAMP
• The TIMESTAMP data type accepts timestamp values, which are a
combination of a DATE value and a TIME value.
• Examples TIMESTAMP
• Valid
• TIMESTAMP `1999-12-31 23:59:59.99'
• TIMESTAMP `2000-01-01 00:00:00'
• Invalid
• 1999-00-00 00:00:00
• TIMESTAMP `1999-01-01 00:64:00'
Example
48
Selecting Rows with
Conditional Restrictions
49
Arithmetic Operators:
DDL statements
The SQL CREATE DATABASE Statement
• The CREATE DATABASE statement is used
to create a new SQL database.
• CREATE DATABASE databasename;
• Exp:
• CREATE DATABASE testDB;
• Table and Column names should be meaningful
and reflect the nature of the data that is to be
stored.
• If the data stored is about the products that a
firm sells , then the table should probably be
named product!
• If products are identified by a string of eight
characters, then the column that stores the
product information data should be named
product_number, or product_code.
Naming Tables and Columns
• One of the first steps in creating a
database is to create the tables that will
store organization’s data.
• In order to create a table , four pieces of
information must be determined:
1. The table name
2. The column (field) names
3. Column data types and
4. Column sizes
Table Creation
SQL CREATE TABLE Statement
• The CREATE TABLE statement is used to create a new
table in a database.
• CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
• The column parameters specify the names of the columns of
the table. The datatype parameter specifies the type of data
the column can hold (e.g. varchar, integer, date, etc.).
• Exp:
• CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
The SQL DROP TABLE Statement
• The DROP TABLE statement is used to drop
an existing table in a database.
• DROP TABLE table_name;
• Exp:
• DROP TABLE Shippers;
SQLALTER TABLE Statement
• The ALTER TABLE statement is used to add,
delete, or modify columns in an existing table.
• The ALTER TABLE statement is also used to
add and drop various constraints on an existing
table.
• ALTER TABLE table_name(
ADD column_name datatype);
ALTER TABLE - DROP COLUMN
• To delete a column in a table, use the
following syntax (notice that some database
systems don't allow deleting a column):
• ALTER TABLE table_name (
DROP COLUMN column_name);
Example:
CREATE TABLE FoodCart (
date varchar(10),
food varchar(20),
profit float
);
ALTER TABLE FoodCart (
ADD sold int
);
ALTER TABLE FoodCart(
DROP COLUMN profit
);
DROP TABLE FoodCart;
profitfooddate
soldprofitfooddate
soldfooddate
FoodCart
FoodCart
FoodCart
SQL: UPDATE Statement
To update the content of the table:
UPDATE statement syntax:
UPDATE table name SET <attr> = <value>
WHERE <selection condition>;
Example: UPDATE FoodCart SET sold = 349
WHERE date = ’02/25/08’AND food = ‘pizza’;
FoodCart FoodCart (updated)
70pizza02/26/08
500hotdog02/26/08
350pizza02/25/08
soldfooddate
70pizza02/26/08
500hotdog02/26/08
349pizza02/25/08
soldfooddate
• Example conditions:
– sold < 40
– food = ‘pizza’
SQL: DELETE Statement
To delete rows from the table:
DELETE statement syntax:
DELETE FROM <table name>
WHERE <condition>;
Example: DELETE FROM FoodCart
WHERE food = ‘hotdog’;
FoodCart
FoodCart
Note: If the WHERE clause is omitted all rows of data are deleted from the table.
70pizza02/26/08
500hotdog02/26/08
349pizza02/25/08
soldfooddate
70pizza02/26/08
349pizza02/25/08
soldfooddate
DML statements
The SELECT statement
• The SELECT statement is the core of SQL,
and it is likely that the vast majority of your
SQL commands will be SELECT statements.
• The SELECT statement is used to query the
database and retrieve selected data that match
the criteria that you specify.
SQL: SELECT Statement
A basic SELECT statement includes 3 clauses
SELECT <attribute name> FROM <tables> WHERE <condition>
SELECT
Specifies the attributes
that are part of the
resulting relation
FROM
Specifies the tables
that serve as the input
to the statement
WHERE
Specifies the selection
condition, including
the join condition.
Note: that you don't need to use WHERE
• SELECT column1, column2, ...
FROM table_name
WHERE condition;
• AND Syntax
• SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND
condition3 ...;
• OR Syntax
• SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR
condition3 ...;
• NOT Syntax
• SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Examples
• SELECT * FROM Customers
WHERE Country='Germany' AND
City='Berlin';
• SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
• SELECT * FROM Customers
WHERE NOT Country='Germany';
• SELECT * FROM Customers
WHERE Country='Germany' AND
(City='Berlin' OR City='München');
• SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT
Country='USA';
Using a “*” in a select statement indicates that
every attribute of the input table is to be selected.
Example: SELECT * FROM … WHERE …;
To get unique rows, type the keyword
DISTINCT after SELECT.
Example: SELECT DISTINCT * FROM …
WHERE …;
SQL: SELECT Statement (cont.)
Example Tables
Student
ID First Last
S103 John Smith
S104 Mary Jones
S105 Jane Brown
S106 Mark Jones
S107 John Brown
Course
Code Title
DBS Database Systems
PR1 Programming 1
PR2 Programming 2
IAI Intro to AI
Grade
ID Code Mark
S103 DBS 72
S103 IAI 58
S104 PR1 68
S104 IAI 65
S106 PR2 43
S107 PR1 76
S107 PR2 60
S107 IAI 35
DISTINCT and ALL
• Sometimes you end up with
duplicate entries
• Using DISTINCT removes
duplicates
• Using ALL retains them -
this is the default
SELECT ALL Last
FROM Student
SELECT DISTINCT Last
FROM Student
Last
Smith
Jones
Brown
Jones
Brown
Last
Smith
Jones
Brown
WHERE Clauses
• Usually you don’t want all
the rows
– A WHERE clause restricts
the rows that are returned
– It takes the form of a
condition - only those rows
that satisfy the condition are
returned
• Example conditions:
– Mark < 40
– First = ‘John’
– First <> ‘John’
– First = Last
– (First = ‘John’) AND
(Last = ‘Smith’)
– (Mark < 40) OR (Mark >
70)
WHERE Examples
SELECT * FROM Grade
WHERE Mark >= 60;
SELECT DISTINCT ID
FROM Grade
WHERE Mark >= 60;
ID Code Mark
S103 DBS 72
S104 PR1 68
S104 IAI 65
S107 PR1 76
S107 PR2 60
ID
S103
S104
S107
Example:
Person
8034Peter
5454Helena
7029George
6428Sally
8034Harry
WeightAgeName
8034Peter
5454Helena
8034Harry
WeightAgeName
80
54
80
Weight
1) SELECT *
FROM person
WHERE age > 30;
2) SELECT weight
FROM person
WHERE age > 30;
3) SELECT distinct weight
FROM person
WHERE age > 30;
54
80
Weight
SQL: The ORDER BY Clause
Ordered result selection
desc (descending order)
SELECT *
FROM emp
order by state desc;
puts state in descending order, e.g. TN, MA, CA
asc (ascending order)
SELECT *
FROM emp
order by id asc;
puts ID in ascending order, e.g. 1001, 1002, 1003
The SQL COUNT(), AVG() and SUM() Functions
• The COUNT() function returns the number of rows that matches a
specified criteria.
• SELECT COUNT(column_name)
FROM table_name
WHERE condition;
• The AVG() function returns the average value of a numeric column.
• SELECT AVG(column_name)
FROM table_name
WHERE condition;
• The SUM() function returns the total sum of a numeric column.
• SELECT SUM(column_name)
FROM table_name
WHERE condition;
As
• Use as to put the output of any operation in new
column and specify this name
• Example:
• SELECT AVG(price) as average;
• The average will calculated for the column of
name price and put the result in a new coulmn of
name average.
SQL: The GROUP BY Clause
The function to divide the tuples into groups and returns an aggregate for each
group.
Usually, it is an aggregate function’s companion
SELECT food, sum(sold) as totalSold
FROM FoodCart
group by food;
FoodCart
419pizza
500hotdog
totalSoldfood
70pizza02/26/08
500hotdog02/26/08
349pizza02/25/08
soldfooddate
The SQL MIN() and MAX() Functions
• The MIN() function returns the smallest value of the
selected column.
• SELECT MIN(column_name)
FROM table_name
WHERE condition;
• The MAX() function returns the largest value of the
selected column.
• SELECT MAX(column_name)
FROM table_name
WHERE condition;
Example
• SELECT MAX(Price) AS LargestPrice
FROM Products;
• SELECT MIN(Price) AS SmallestPrice
FROM Products;
SELECT from Multiple Tables
• Often you need to combine
information from two or
more tables
• You can get the effect of a
product by using
SELECT * FROM Table1, Table2...
• If the tables have columns
with the same name
ambiguity results
• You resolve this by
referencing columns with
the table name
TableName.Column
SELECT from Multiple Tables
ID First Last ID Code Mark
S103 John Smith S103 DBS 72
S103 John Smith S103 IAI 58
S104 Mary Jones S104 PR1 68
S104 Mary Jones S104 IAI 65
S106 Mark Jones S106 PR2 43
S107 John Brown S107 PR1 76
S107 John Brown S107 PR2 60
SELECT ... FROM Student, Grade
WHERE (Student.ID = Grade.ID) AND (Mark >= 40);
Student
ID First Last
S103 John Smith
S104 Mary Jones
S105 Jane Brown
S106 Mark Jones
S107 John Brown
Grade
ID Code Mark
S103 DBS 72
S103 IAI 58
S104 PR1 68
S104 IAI 65
S106 PR2 43
S107 PR1 76
S107 PR2 60
S107 IAI 35
SELECT from Multiple Tables
• Suppose you have
another table, with
name course
Find the output of the
following statements:
SELECT * FROM
Student, Grade, Course
WHERE
Student.ID = Grade.ID
AND
Course.Code = Grade.Code
SELECT from Multiple Tables
ID First Last ID Code Mark Code Title
S103 John Smith S103 DBS 72 DBS Database Systems
S103 John Smith S103 IAI 58 IAI Intro to AI
S104 Mary Jones S104 PR1 68 PR1 Programming 1
S104 Mary Jones S104 IAI 65 IAI Intro to AI
S106 Mark Jones S106 PR2 43 PR2 Programming 2
S107 John Brown S107 PR1 76 PR1 Programming 1
S107 John Brown S107 PR2 60 PR2 Programming 2
S107 John Brown S107 IAI 35 IAI Intro to AI
Student Grade Course
Student.ID = Grade.ID Course.Code = Grade.Code
SELECT * FROM Student, Grade, Course
WHERE
Student.ID = Grade.ID AND Course.Code = Grade.Code
SQL: Join operation
A join (inner join) can be specified in the FROM
clause which list the two input relations.
Example:
Biotech1003
Sales1002
IT1001
DivisionID
TN1002
MA1001
CA1000
StateID
Emp Dept
SQL: Join operation (cont.)
Sales1002
IT1001
Dept.DivisionDept.ID
TN1002
MA1001
Emp.StateEmp.ID
inner join = join
SELECT *
FROM emp join dept (or FROM emp, dept)
ON emp.id = dept.id;
Biotech1003
Sales1002
IT1001
DivisionID
TN1002
MA1001
CA1000
StateIDEmp Dept
INSERT INTO Syntax
• The INSERT INTO statement is used to insert
new records in a table.
• INSERT INTO table_name (column1,
column2, column3, ...)
•
VALUES (value1, value2, value3, ...);
Example: INSERT into FoodCart
VALUES (’02/26/08', ‘pizza', 70 );
FoodCart
70pizza02/26/08
500hotdog02/26/08
350pizza02/25/08
soldfooddate
500hotdog02/26/08
350pizza02/25/08
soldfooddate
Comments
• comments start with /* and end with */.
• Any text between /* and */ will be ignored.
• /*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;
SQL Constraints
• SQL constraints are used to specify rules for the data in a table.
• If there is any violation between the constraint and the data action,
the action is aborted.
• Constraints can be column level or table level. Column level
constraints apply to a column, and table level constraints apply to
the whole table.
• Examples of constraints:
• keys, domain constraints, tuple constraints.
SQL contrains
• The following constraints are commonly used in SQL:
• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• CHECK - Ensures that all values in a column satisfies a specific condition
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE.
Uniquely identifies each row in a table
• FOREIGN KEY - Uniquely identifies a row/record in another table
• DEFAULT - Sets a default value for a column when no value is specified
SQL NOT NULL Constraint
• By default, a column can hold NULL values.
• The NOT NULL constraint enforces a column
to NOT accept NULL values.
• This enforces a field to always contain a value,
which means that you cannot insert a new
record, or update a record without adding a
value to this field.
• Exp:
• CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
SQL UNIQUE Constraint
• The UNIQUE constraint ensures that all values in a column
are different.
• Both the UNIQUE and PRIMARY KEY constraints provide
a guarantee for uniqueness for a column or set of columns.
• A PRIMARY KEY constraint automatically has a UNIQUE
constraint.
• However, you can have many UNIQUE constraints per
table, but only one PRIMARY KEY constraint per table.
• CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
Check or Table Constraints
CREATE TABLE Sailors
( sid INTEGER,
sname CHAR(10),
rating INTEGER,
age REAL,
CHECK ( rating >= 1 AND rating <= 10 ));
Check constrain keep the values in the attribute
rating between 1 and 10
SQL PRIMARY KEY Constraint
• The PRIMARY KEY constraint uniquely
identifies each record in a database table.
• Primary keys must contain UNIQUE values,
and cannot contain NULL values.
• A table can have only one primary key, which
may consist of single or multiple fields.
• CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
SQL PRIMARY KEY on ALTER TABLE
• To create a PRIMARY KEY constraint on the
"ID" column when the table is already created,
use the following SQL:
• ALTER TABLE Persons
ADD PRIMARY KEY (ID);
• ALTER TABLE Persons
DROP PRIMARY KEY;
SQL FOREIGN KEY CONSTRAINT
• The SQL FOREIGN KEY CONSTRAINT is used
to ensure the referential integrity of the data in
one table to match values in another table.
The FOREIGN KEY CONSTRAINT is a column
or list of columns which points to the PRIMARY
KEY of another table.
The main purpose of FOREIGN KEY is, only
those values will appear which are present in the
primary key table.
Field Name Data Type Size
Decimal
Places
NULL Constraint
agent_code char 6 No
PRIMARY
KEY
agent_name char 40 No
working_area char 35 Yes
commission decimal 10 2 Yes
phone_no char 17 Yes
agents
Field Name Data Type Size
Decimal
Places
NULL Constraint
cust_code char 6 No
PRIMARY
KEY
cust_name char 25 Yes
cust_city char 25 Yes
agent_code char 6 Yes
FOREIGN
KEY
customer1
Example
• SQL Code:
• CREATE TABLE customer1(
• cust_code char(6) NOT NULL PRIMARY KEY,
• cust_name char(25),
• cust_city char(25),
• agent_code char(6),
• FOREIGN KEY(agent_code)
• REFERENCES agents (agent_code) ) ;
SQL DEFAULT Constraint
• The DEFAULT constraint is used to provide a
default value for a column.
• The default value will be added to all new
records IF no other value is specified.
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
Example
Example: Using Table Constraints
More examples on SQL
106
Rows describe
the Occurrence
of an Entity
Table Design
Name Address
Jane Doe 123 Main Street
John Smith 456 Second Street
Mary Poe 789 Third Ave
Columns describe one
characteristic of the entity
107
Using SQL
To begin, you must first CREATE a database using the
following SQL statement:
CREATE DATABASE database_name
108
Using SQL
• To create a table in the current database,
use the CREATE TABLE keyword
CREATE TABLE authors
(auth_id int(9) not null,
auth_name char(40) not null)
auth_id auth_name
(9 digit int) (40 char string)
109
Data Retrieval (Queries)
• Queries search the database, fetch info,
and display it. This is done using the
keyword SELECT
SELECT * FROM publishers
pub_id pub_name address state
0736 New Age Books 1 1st Street MA
0987 Binnet & Hardley 2 2nd Street DC
1120 Algodata Infosys 3 3rd Street CA
The
*Operator asks for every column in the table.
110
Data Retrieval (Queries)
• Queries can be more specific with a few
more lines
pub_id pub_name address state
0736 New Age Books 1 1st Street MA
0987 Binnet & Hardley 2 2nd Street DC
1120 Algodata Infosys 3 3rd Street CA
Only publishers in CA are displayed
SELECT *
from publishers
where state = ‘CA’
111
Data Input
• Putting data into a table is accomplished
using the keyword INSERT
pub_id pub_name address state
0736 New Age Books 1 1st Street MA
0987 Binnet & Hardley 2 2nd Street DC
1120 Algodata Infosys 3 3rd Street CA
Table is updated with new information
INSERT INTO publishers
VALUES (‘0010’, ‘pragmatics’, ‘4 4th Ln’, ‘il’)
pub_id pub_name address state
0010 Pragmatics 4 4th Ln IL
0736 New Age Books 1 1st Street MA
0987 Binnet & Hardley 2 2nd Street DC
1120 Algodata Infosys 3 3rd Street CA
Keyword
Variable
112
Using SQL
• To insert data in the current table, use the
keyword INSERT INTO
auth_id auth_name
Then issue the statement
SELECT * FROM authors
INSERT INTO authors
values(‘000000001’, ‘John Smith’)
000000001 John Smith
113
Using SQL
SELECT auth_name, auth_city
FROM publishers
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI
000000001 John Smith Taylor MI
auth_name auth_city
Jane Doe Dearborn
John Smith Taylor
If you only want to display the author’s name and city from the following
table:
114
Using SQL
DELETE from authors
WHERE auth_name=‘John Smith’
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI
000000001 John Smith Taylor MI
To delete data from a table, use the DELETE statement:
115
Using SQL
UPDATE authors
SET auth_name=‘hello’
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI
000000001 John Smith Taylor MI
To Update information in a database use the UPDATE keyword
Hello
Hello
Sets all auth_name fields to hello
116
Using SQL
ALTER TABLE authors
ADD birth_date datetime null
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI
000000001 John Smith Taylor MI
To change a table in a database use ALTER TABLE. ADD adds a characteristic.
ADD puts a new column in the table called birth_date
birth_date
.
.
117
Using SQL
ALTER TABLE authors
DROP birth_date
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI
000000001 John Smith Taylor MI
To delete a column or row, use the keyword DROP
DROP removed the birth_date characteristic from the table
auth_state
.
.
118
Using SQL
DROP DATABASE authors
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI
000000001 John Smith Taylor MI
The DROP statement is also used to delete an entire database.
DROP removed the database and returned the memory to system
SQL examples
• CREATE TABLE STATION
(ID INTEGER PRIMARY KEY,
CITY CHAR(20),
STATE CHAR(2),
LAT_N REAL,
LONG_W REAL);
• INSERT INTO STATION VALUES (13, 'Phoenix', 'AZ', 33, 112);
INSERT INTO STATION VALUES (44, 'Denver', 'CO', 40, 105);
INSERT INTO STATION VALUES (66, 'Caribou', 'ME', 47, 68);
• SELECT LAT_N, CITY, TEMP_F
FROM STATS, STATION
WHERE MONTH = 7
AND STATS.ID = STATION.ID
ORDER BY TEMP_F;
Compiling between relational algebra& SQL
120
121
SQL Quick Reference
SQL Statement Syntax
AND / OR
SELECT column_name(s)
FROM table_name
WHERE condition
AND|OR condition
ALTER TABLE
ALTER TABLE table_name
ADD column_name datatypeor
ALTER TABLE table_name
DROP COLUMN column_name
AS (alias)
SELECT column_name AS column_alias
FROM table_nameor
SELECT column_name
FROM table_name AS table_alias
CREATE VIEW
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
BETWEEN
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
CREATE DATABASE CREATE DATABASE database_name
CREATE TABLE
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
...
)
CREATE INDEX
CREATE INDEX index_name
ON table_name (column_name)or
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
DELETE
DELETE FROM table_name
WHERE some_column=some_valueor
DELETE FROM table_name
(Note: Deletes the entire table!!)
DELETE * FROM table_name
(Note: Deletes the entire table!!)
DROP DATABASE DROP DATABASE database_name
DROP INDEX
DROP INDEX table_name.index_name
(SQL Server)
DROP INDEX index_name ON
table_name (MS Access)
DROP INDEX index_name (DB2/Oracle)
ALTER TABLE table_name
DROP INDEX index_name (MySQL)
DROP TABLE DROP TABLE table_name
EXISTS
IF EXISTS (SELECT * FROM table_name WHERE id =
?)
BEGIN
--do what needs to be done if exists
END
ELSE
BEGIN
--do what needs to be done if not
END
GROUP BY
SELECT column_name,
aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING
SELECT column_name,
aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator
value
IN
SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)
INSERT INTO
INSERT INTO table_name
VALUES (value1, value2, value3,....)or
INSERT INTO table_name
(column1, column2, column3,...)
VALUES (value1, value2, value3,....)
INNER JOIN
SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
LEFT JOIN
SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
RIGHT JOIN
SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON
table_name1.column_name=table_name2.colum
n_name
FULL JOIN
SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON
table_name1.column_name=table_name2.colum
n_name
LIKE
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
ORDER BY
SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC|DESC]
SELECT
SELECT column_name(s)
FROM table_name
SELECT *
SELECT *
FROM table_name
SELECT DISTINCT
SELECT DISTINCT column_name(s)
FROM table_name
SELECT INTO
SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_table_nameor
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name
SELECT TOP
SELECT TOP number|percent
column_name(s)
FROM table_name
TRUNCATE TABLE TRUNCATE TABLE table_name
UNION
SELECT column_name(s) FROM
table_name1
UNION
SELECT column_name(s) FROM
table_name2
UNION ALL
SELECT column_name(s) FROM
table_name1
UNION ALL
SELECT column_name(s) FROM
table_name2
UPDATE
UPDATE table_name
SET column1=value, column2=value,...
WHERE some_column=some_value
WHERE
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
End part 2

More Related Content

What's hot

Oracle Insert Statements for DBAs and Developers
Oracle Insert Statements for DBAs and DevelopersOracle Insert Statements for DBAs and Developers
Oracle Insert Statements for DBAs and DevelopersGuatemala User Group
 
What is SQL Server?
What is SQL Server?What is SQL Server?
What is SQL Server?CPD INDIA
 
2008 2086 Gangler
2008 2086 Gangler2008 2086 Gangler
2008 2086 GanglerSecure-24
 
A Practitioner's Guide to Successfully Migrate from Oracle to Sybase ASE Part 1
A Practitioner's Guide to Successfully Migrate from Oracle to Sybase ASE Part 1A Practitioner's Guide to Successfully Migrate from Oracle to Sybase ASE Part 1
A Practitioner's Guide to Successfully Migrate from Oracle to Sybase ASE Part 1Dobler Consulting
 
PostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | EdurekaPostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | EdurekaEdureka!
 
Database Programming
Database ProgrammingDatabase Programming
Database ProgrammingHenry Osborne
 
Presentation online application upgrade of oracle's bug db with edition-ba...
Presentation    online application upgrade of oracle's bug db with edition-ba...Presentation    online application upgrade of oracle's bug db with edition-ba...
Presentation online application upgrade of oracle's bug db with edition-ba...xKinAnx
 

What's hot (20)

Java full stack1
Java full stack1Java full stack1
Java full stack1
 
Dbms &amp; oracle
Dbms &amp; oracleDbms &amp; oracle
Dbms &amp; oracle
 
Oracle Insert Statements for DBAs and Developers
Oracle Insert Statements for DBAs and DevelopersOracle Insert Statements for DBAs and Developers
Oracle Insert Statements for DBAs and Developers
 
Sybase To Oracle Migration for DBAs
Sybase To Oracle Migration for DBAsSybase To Oracle Migration for DBAs
Sybase To Oracle Migration for DBAs
 
What is SQL Server?
What is SQL Server?What is SQL Server?
What is SQL Server?
 
2008 2086 Gangler
2008 2086 Gangler2008 2086 Gangler
2008 2086 Gangler
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Create table
Create tableCreate table
Create table
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Module02
Module02Module02
Module02
 
T-SQL Overview
T-SQL OverviewT-SQL Overview
T-SQL Overview
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
A Practitioner's Guide to Successfully Migrate from Oracle to Sybase ASE Part 1
A Practitioner's Guide to Successfully Migrate from Oracle to Sybase ASE Part 1A Practitioner's Guide to Successfully Migrate from Oracle to Sybase ASE Part 1
A Practitioner's Guide to Successfully Migrate from Oracle to Sybase ASE Part 1
 
PostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | EdurekaPostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | Edureka
 
Database Programming
Database ProgrammingDatabase Programming
Database Programming
 
Introduction to mysql part 1
Introduction to mysql part 1Introduction to mysql part 1
Introduction to mysql part 1
 
Presentation online application upgrade of oracle's bug db with edition-ba...
Presentation    online application upgrade of oracle's bug db with edition-ba...Presentation    online application upgrade of oracle's bug db with edition-ba...
Presentation online application upgrade of oracle's bug db with edition-ba...
 
Sql commands
Sql commandsSql commands
Sql commands
 

Similar to Database part2-

Sql server difference faqs- 6
Sql server difference faqs- 6Sql server difference faqs- 6
Sql server difference faqs- 6Umar Ali
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptxKulbir4
 
B.Vinithamani,II-M.sc.,Computer science,Bon Secours college for women,thanjavur.
B.Vinithamani,II-M.sc.,Computer science,Bon Secours college for women,thanjavur.B.Vinithamani,II-M.sc.,Computer science,Bon Secours college for women,thanjavur.
B.Vinithamani,II-M.sc.,Computer science,Bon Secours college for women,thanjavur.vinithamaniB
 
Natural Language to SQL Query conversion using Machine Learning Techniques on...
Natural Language to SQL Query conversion using Machine Learning Techniques on...Natural Language to SQL Query conversion using Machine Learning Techniques on...
Natural Language to SQL Query conversion using Machine Learning Techniques on...HPCC Systems
 
Understanding the SQL aspects of Spark - Spark SQL.pptx
Understanding the SQL aspects of Spark - Spark SQL.pptxUnderstanding the SQL aspects of Spark - Spark SQL.pptx
Understanding the SQL aspects of Spark - Spark SQL.pptxKnoldus Inc.
 
U-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersU-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersMichael Rys
 
Access Data from XPages with the Relational Controls
Access Data from XPages with the Relational ControlsAccess Data from XPages with the Relational Controls
Access Data from XPages with the Relational ControlsTeamstudio
 
Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Vidyasagar Mundroy
 
Building scalable application with sql server
Building scalable application with sql serverBuilding scalable application with sql server
Building scalable application with sql serverChris Adkin
 
Sql and its functions
Sql and its functionsSql and its functions
Sql and its functionsRohit Kumar
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytWrushabhShirsat3
 
Querying_with_T-SQL_-_01.pptx
Querying_with_T-SQL_-_01.pptxQuerying_with_T-SQL_-_01.pptx
Querying_with_T-SQL_-_01.pptxQuyVo27
 
MODULE 5.pptx
MODULE 5.pptxMODULE 5.pptx
MODULE 5.pptxlathass5
 
MySQL Baics - Texas Linxufest beginners tutorial May 31st, 2019
MySQL Baics - Texas Linxufest beginners tutorial May 31st, 2019MySQL Baics - Texas Linxufest beginners tutorial May 31st, 2019
MySQL Baics - Texas Linxufest beginners tutorial May 31st, 2019Dave Stokes
 

Similar to Database part2- (20)

DBMS UNIT 3
DBMS UNIT 3DBMS UNIT 3
DBMS UNIT 3
 
Sql server difference faqs- 6
Sql server difference faqs- 6Sql server difference faqs- 6
Sql server difference faqs- 6
 
SQL 3.pptx
SQL 3.pptxSQL 3.pptx
SQL 3.pptx
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptx
 
Sql
SqlSql
Sql
 
B.Vinithamani,II-M.sc.,Computer science,Bon Secours college for women,thanjavur.
B.Vinithamani,II-M.sc.,Computer science,Bon Secours college for women,thanjavur.B.Vinithamani,II-M.sc.,Computer science,Bon Secours college for women,thanjavur.
B.Vinithamani,II-M.sc.,Computer science,Bon Secours college for women,thanjavur.
 
Natural Language to SQL Query conversion using Machine Learning Techniques on...
Natural Language to SQL Query conversion using Machine Learning Techniques on...Natural Language to SQL Query conversion using Machine Learning Techniques on...
Natural Language to SQL Query conversion using Machine Learning Techniques on...
 
Understanding the SQL aspects of Spark - Spark SQL.pptx
Understanding the SQL aspects of Spark - Spark SQL.pptxUnderstanding the SQL aspects of Spark - Spark SQL.pptx
Understanding the SQL aspects of Spark - Spark SQL.pptx
 
U-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersU-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for Developers
 
Access Data from XPages with the Relational Controls
Access Data from XPages with the Relational ControlsAccess Data from XPages with the Relational Controls
Access Data from XPages with the Relational Controls
 
Unit 04 dbms
Unit 04 dbmsUnit 04 dbms
Unit 04 dbms
 
Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)
 
Building scalable application with sql server
Building scalable application with sql serverBuilding scalable application with sql server
Building scalable application with sql server
 
Sql and its functions
Sql and its functionsSql and its functions
Sql and its functions
 
Pl sql content
Pl sql contentPl sql content
Pl sql content
 
unit-ii.pptx
unit-ii.pptxunit-ii.pptx
unit-ii.pptx
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
 
Querying_with_T-SQL_-_01.pptx
Querying_with_T-SQL_-_01.pptxQuerying_with_T-SQL_-_01.pptx
Querying_with_T-SQL_-_01.pptx
 
MODULE 5.pptx
MODULE 5.pptxMODULE 5.pptx
MODULE 5.pptx
 
MySQL Baics - Texas Linxufest beginners tutorial May 31st, 2019
MySQL Baics - Texas Linxufest beginners tutorial May 31st, 2019MySQL Baics - Texas Linxufest beginners tutorial May 31st, 2019
MySQL Baics - Texas Linxufest beginners tutorial May 31st, 2019
 

More from Taymoor Nazmy

Artificial intelligent Lec 5-logic
Artificial intelligent Lec 5-logicArtificial intelligent Lec 5-logic
Artificial intelligent Lec 5-logicTaymoor Nazmy
 
Artificial intelligent Lec 3-ai chapter3-search
Artificial intelligent Lec 3-ai chapter3-searchArtificial intelligent Lec 3-ai chapter3-search
Artificial intelligent Lec 3-ai chapter3-searchTaymoor Nazmy
 
Artificial intelligent Lec 1-ai-introduction-
Artificial intelligent Lec 1-ai-introduction-Artificial intelligent Lec 1-ai-introduction-
Artificial intelligent Lec 1-ai-introduction-Taymoor Nazmy
 
Image processing 1-lectures
Image processing  1-lecturesImage processing  1-lectures
Image processing 1-lecturesTaymoor Nazmy
 
Software Engineering Lec 10 -software testing--
Software Engineering Lec 10 -software testing--Software Engineering Lec 10 -software testing--
Software Engineering Lec 10 -software testing--Taymoor Nazmy
 
Software Engineering Lec 8-design-
Software Engineering Lec 8-design-Software Engineering Lec 8-design-
Software Engineering Lec 8-design-Taymoor Nazmy
 
Software Engineering Lec 7-uml-
Software Engineering Lec 7-uml-Software Engineering Lec 7-uml-
Software Engineering Lec 7-uml-Taymoor Nazmy
 
Software Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iSoftware Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iTaymoor Nazmy
 
Software Engineering Lec 4-requirments
Software Engineering Lec 4-requirmentsSoftware Engineering Lec 4-requirments
Software Engineering Lec 4-requirmentsTaymoor Nazmy
 
Software Engineering Lec 3-project managment
Software Engineering Lec 3-project managmentSoftware Engineering Lec 3-project managment
Software Engineering Lec 3-project managmentTaymoor Nazmy
 
Software Engineering Lec 2
Software Engineering Lec 2Software Engineering Lec 2
Software Engineering Lec 2Taymoor Nazmy
 
Software Engineering Lec 1-introduction
Software Engineering Lec 1-introductionSoftware Engineering Lec 1-introduction
Software Engineering Lec 1-introductionTaymoor Nazmy
 

More from Taymoor Nazmy (20)

Cognitive systems
Cognitive  systemsCognitive  systems
Cognitive systems
 
Cognitive systems
Cognitive  systemsCognitive  systems
Cognitive systems
 
Artificial intelligent Lec 5-logic
Artificial intelligent Lec 5-logicArtificial intelligent Lec 5-logic
Artificial intelligent Lec 5-logic
 
Artificial intelligent Lec 3-ai chapter3-search
Artificial intelligent Lec 3-ai chapter3-searchArtificial intelligent Lec 3-ai chapter3-search
Artificial intelligent Lec 3-ai chapter3-search
 
Lec 2-agents
Lec 2-agentsLec 2-agents
Lec 2-agents
 
Artificial intelligent Lec 1-ai-introduction-
Artificial intelligent Lec 1-ai-introduction-Artificial intelligent Lec 1-ai-introduction-
Artificial intelligent Lec 1-ai-introduction-
 
Image processing 2
Image processing 2Image processing 2
Image processing 2
 
Image processing 1-lectures
Image processing  1-lecturesImage processing  1-lectures
Image processing 1-lectures
 
Software Engineering Lec 10 -software testing--
Software Engineering Lec 10 -software testing--Software Engineering Lec 10 -software testing--
Software Engineering Lec 10 -software testing--
 
Software Engineering Lec 8-design-
Software Engineering Lec 8-design-Software Engineering Lec 8-design-
Software Engineering Lec 8-design-
 
Software Engineering Lec 7-uml-
Software Engineering Lec 7-uml-Software Engineering Lec 7-uml-
Software Engineering Lec 7-uml-
 
Software Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iSoftware Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-i
 
Software Engineering Lec 4-requirments
Software Engineering Lec 4-requirmentsSoftware Engineering Lec 4-requirments
Software Engineering Lec 4-requirments
 
Software Engineering Lec 3-project managment
Software Engineering Lec 3-project managmentSoftware Engineering Lec 3-project managment
Software Engineering Lec 3-project managment
 
Software Engineering Lec 2
Software Engineering Lec 2Software Engineering Lec 2
Software Engineering Lec 2
 
Software Engineering Lec 1-introduction
Software Engineering Lec 1-introductionSoftware Engineering Lec 1-introduction
Software Engineering Lec 1-introduction
 
Lec 6-
Lec 6-Lec 6-
Lec 6-
 
presentation skill
presentation skillpresentation skill
presentation skill
 
Lec 4
Lec 4Lec 4
Lec 4
 
Lec 3
Lec 3Lec 3
Lec 3
 

Recently uploaded

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 

Recently uploaded (20)

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 

Database part2-

  • 1. Course code: ITI131 Course title : Database PART: 2 Prof. Taymoor Mohamed Nazmy Dept. of computer science, faculty of computer science, Ain Shams uni. Ex-vice dean of post graduate studies and research Cairo, Egypt 1
  • 3. Relational algebra, SQL, and the DBMS? parser SQL Relational algebra expression Optimized Relational algebra expression Query optimizer Code generator Query execution plan Executable code DBMS
  • 4. Introduction • Query language is a language in which user requests information from the database. it can be categorized as either procedural or nonprocedural. • In a procedural language the user instructs the system to do a sequence of operations on database to compute the desired result. • In nonprocedural language the user describes the desired information without giving a specific procedure for obtaining that information. • The relational algebra is a procedural query language. It consists of a set of operations that take one or two relations as input and produces a new relation as output
  • 5. 5 Relational Query Languages • Languages for describing queries on a relational database • Structured Query Language (SQL) – Predominant application-level query language – Declarative • Relational Algebra – Intermediate language used within DBMS – Procedural • To process a query, a DBMS translates SQL into a notation similar to relational algebra.
  • 6. Relational Algebra • Relational Algebra is a procedural language that can be used to tell the DBMS ( Data Base Management System) how to build a new relation from one or more relations in the database. 6
  • 7. 7 Formal Relational Query Languages Two mathematical Query Languages form the basis for formal relational query languages: • Relational Algebra: More operational, very useful for representing execution plans. • Relational Calculus: Lets users describe what they want, rather than how to compute it. (Non-operational, declarative.)  Understanding Algebra & Calculus is key to  understanding SQL, query processing!
  • 10. 10 Example Instances sid sname rating age 22 dustin 7 45.0 31 lubber 8 55.5 58 rusty 10 35.0 sid sname rating age 28 yuppy 9 35.0 31 lubber 8 55.5 44 guppy 5 35.0 58 rusty 10 35.0 sid bid day 22 101 10/10/96 58 103 11/12/96 R1 S1 S2 • Consider the following instances R1, S1, S2.
  • 11. Basic Relational Algebra Operations (Unary): Selection, Projection Selection:  <condition(s)> (<relation>) • Picks tuples from the relation Projection:  <attribute-list> (<relation>) • Picks columns from the relation
  • 12. 12 Selection (  ) rating S 8 2( ) sid sname rating age 28 yuppy 9 35.0 58 rusty 10 35.0 sname rating yuppy 9 rusty 10 ))2( 8 ( , S ratingratingsname   • Selects rows that satisfy selection condition. • No duplicates in result! (Why?) • Schema of result identical to schema of (only) input relation. • Result relation can be the input for another relational algebra operation! (Operator composition.) S2 sid sname rating age 28 yuppy 9 35.0 31 lubber 8 55.5 44 guppy 5 35.0 58 rusty 10 35.0
  • 13. 13 Projection ( ) sname rating yuppy 9 lubber 8 guppy 5 rusty 10 sname rating S , ( )2 age 35.0 55.5 age S( )2 • Deletes attributes that are not in projection list. • Schema of result contains exactly the fields in the projection list, with the same names that they had in the (only) input relation. • Projection operator has to eliminate duplicates! sid sname rating age 28 yuppy 9 35.0 31 lubber 8 55.5 44 guppy 5 35.0 58 rusty 10 35.0 S2
  • 14. Relational Algebra Operations (Set): Union, Set Difference, and intersection Union: (<relation>) U (<relation>) • New relation contains all tuples from both relations, duplicate tuples eliminated. Set Difference: R – S • Produces a relation with tuples that are in R but NOT in S. Intersection: R S • All tuples that are in both R and S
  • 15. 15 Union, Intersection, Set-Difference sid sname rating age 22 dustin 7 45.0 31 lubber 8 55.5 58 rusty 10 35.0 44 guppy 5 35.0 28 yuppy 9 35.0 sid sname rating age 31 lubber 8 55.5 58 rusty 10 35.0 S S1 2 S S1 2 sid sname rating age 22 dustin 7 45.0 S S1 2 sid sname rating age 28 yuppy 9 35.0 31 lubber 8 55.5 44 guppy 5 35.0 58 rusty 10 35.0 S2 sid sname rating age 22 dustin 7 45.0 31 lubber 8 55.5 58 rusty 10 35.0 S1
  • 16. Relational Algebra Operations (Set): Cartesian Product, Intersect Cartesian Product: R x S • Produces a relation that is concatenation of every tuple of R with every tuple of S • The Above operations are the 5 fundamental operations of relational algebra.
  • 17. 17 Cross-Product () • S1  R1 : Each row of S1 is paired with each row of R1. • Result schema has one field per field of S1 and R1, with field names `inherited’ if possible. – Conflict: Both S1 and R1 have a field called sid. (sid) sname rating age (sid) bid day 22 dustin 7 45.0 22 101 10/10/96 22 dustin 7 45.0 58 103 11/12/96 31 lubber 8 55.5 22 101 10/10/96 31 lubber 8 55.5 58 103 11/12/96 58 rusty 10 35.0 22 101 10/10/96 58 rusty 10 35.0 58 103 11/12/96 sid sname rating age 22 dustin 7 45.0 31 lubber 8 55.5 58 rusty 10 35.0 sid bid day 22 101 10/10/96 58 103 11/12/96 R1 S1
  • 19. Introduction • SQl designed for managing data held in a relational database management system (RDBMS), • Originally based upon relational algebra and tuple relational calculus, SQL consists of a data definition language, data manipulation language, and data control language. • The scope of SQL includes data insert, query, update and delete, schema creation and modification, and data access control.
  • 20. History of SQL • SQL: Structured Query Language, used to be called SEQEL • SQL is based on the relational tuple calculus • SEQUEL: It was designed by IBM Research as the interface for an experimental relational database system called SYSTEM R. 1974. • SQL/86: ANSI & ISO standard • SQL/89: ANSI & ISO standard • SQL/92 or SQL2: ANSI & ISO standard • SQL3: in the works... • SQL2 supported by RDMS such as: • ORACLE, SYBASE, INFORMIX, IBM DB2, SQL SERVER, and Open Source’s MySQL,
  • 21. Extended Versions of SQL • However most Database Management Systems (DBMS) provide non-standard extensions to SQL that include procedural elements, the following table show some of those extensions: Source Common name Full name ANSI/ISO Standard SQL/PSM SQL/Persistent Stored Modules Interbase / Firebird PSQL Procedural SQL IBM DB2 SQL PL SQL Procedural Language (implements SQL/PSM) IBM Informix SPL Stored Procedural Language IBM Netezza NZPLSQL[18] (based on Postgres PL/pgSQL) Microsoft / Sybase T-SQL Transact-SQL Mimer SQL SQL/PSM SQL/Persistent Stored Module (implements SQL/PSM) MySQL SQL/PSM SQL/Persistent Stored Module (implements SQL/PSM) MonetDB SQL/PSM SQL/Persistent Stored Module (implements SQL/PSM) NuoDB SSP Starkey Stored Procedures Oracle PL/SQL Procedural Language/SQL (based on Ada) PostgreSQL PL/pgSQL Procedural Language/PostgreSQL Structured Query Language (implements SQL/PSM) Sybase Watcom-SQL SQLAnywhere Watcom-SQL Dialect Teradata SPL Stored Procedural Language SAP SAP HANA SQL Script
  • 22. MySQL 2/7/2020  MySQL is the world's most popular open source database software, with over 100 million copies of its software downloaded or distributed throughout it's history.  MySQL is a relational database management system ( RDBMS ) and which runs a server, providing multi-user access to a number of databases.  With its superior speed, reliability, and ease of use, MySQL has become the preferred choice for IT in all sectors or domains.
  • 23. What is SQL? • When a user wants to get some information • from a database file, he can issue a query. • – A query is a user–request to retrieve data or • information with a certain condition. • – SQL is a query language that allows user to • specify the conditions. (instead of algorithms) 23
  • 24. SQL language is divided into four types
  • 25. DML (Data Manipulation Language) • DML statements affect records in a table. These are basic operations we perform on data such as selecting a few records from a table, inserting new records, deleting unnecessary records, and updating/modifying existing records. • DML statements include the following: • SELECT – select records from a table INSERT – insert new records UPDATE – update/Modify existing records DELETE – delete existing records
  • 26. DDL (Data Definition Language) • DDL statements are used to alter/modify a database or table structure and schema. These statements handle the design and storage of database objects. • CREATE – create a new Table, database, schema ALTER – alter existing table, column description DROP – delete existing objects from database
  • 27. DCL (Data Control Language) • DCL statements control the level of access that users have on database objects. • GRANT – allows users to read/write on certain database objects • REVOKE – keeps users from read/write permission on database objects
  • 28. TCL (Transaction Control Language) • TCL statements allow you to control and manage transactions to maintain the integrity of data within SQL statements. • BEGIN Transaction – opens a transaction COMMIT Transaction – commits a transaction • ROLLBACK Transaction – ROLLBACK a transaction in case of any error
  • 29. Using SQL in Your Web Site • To build a web site that shows data from a database, you will need: • An RDBMS database program (i.e. MS Access, SQL Server, MySQL) • To use a server-side scripting language, like PHP or ASP • To use SQL to get the data you want to use HTML / CSS to style the page
  • 30. 30 Using SQL SQL statements can be embedded into a program (cgi or perl script, Visual Basic, MS Access) OR SQL statements can be entered directly at the command prompt of the SQL software being used (such as mySQL)
  • 31. Keep in Mind that • SQL keywords are NOT case sensitive: select is the same as SELECT. • Some database systems require a semicolon at the end of each SQL statement. • Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server.
  • 32. SQL Statements, Operations, Clauses SQL Statements such as : Select SQL Operations such as: Join Left Join Right Join Like SQL Clauses such as: Order By Group By Having
  • 33. Some of The Most Important SQL Statements • SELECT - extracts data from a database • UPDATE - updates data in a database • DELETE - deletes data from a database • INSERT INTO - inserts new data into a database • CREATE DATABASE - creates a new database • ALTER DATABASE - modifies a database • CREATE TABLE - creates a new table • ALTER TABLE - modifies a table • DROP TABLE - deletes a table • CREATE INDEX - creates an index (search key) • DROP INDEX - deletes an index
  • 34. Learning and execute SQl online • https://www.w3schools.com/sql/default.asp
  • 35. SQL: Attributes Types (data type)
  • 36. CHARACTER [(length)] or CHAR [(length)] • The CHARACTER data type accepts character strings, including Unicode, of a fixed length. The length of the character string should be specified in the data type declaration; for example, CHARACTER(n) where n represents the desired length of the character string. • If no length is specified during the declaration, the default length is 1. Used to store character string value of fixed length. • The maximum no. of characters the data type can hold is 255 characters. It's 50% faster than VARCHAR. Any remaining space in the field is padded with blanks.
  • 37. CHARACTER [(length)] or CHAR [(length)] • CHAR(10) or CHARACTER(10) • Valid • 'Race car' • 'RACECAR' • '24865' • '1998-10-25' • '1998-10-25 ' (Blank characters are truncated) • Invalid 24865 1998-10-25 'Date: 1998-10-25'
  • 38. VARCHAR (length) • The VARCHAR data type accepts character strings, including Unicode, of a variable length is up to the maximum length specified in the data type declaration. • Examples • VARCHAR(10) • Valid • 'Race car' • 'RACECAR' • '24865' • '1998-10-25' • '1998-10-25 ' Invalid 24865 1998-10-25 'Date: 1998-10-25'
  • 39. BOOLEAN • The BOOLEAN data type supports the storage of two values: TRUE or FALSE. No parameters are required when declaring a BOOLEAN data type. • Examples • BOOLEAN • Valid • TRUE • true • True • False Invalid 1 0 Yes No
  • 40. SMALLINT • The SMALLINT data type accepts numeric values with an implied scale of zero. It stores any integer value between the range 2^ -15 and 2^15-1. • SMALLINT • Valid • -32768 • 0 • -30.3 (digits to the right of the • decimal point are truncated) • 32767 Invalid -33,000,567 1,897,536,000
  • 41. INTEGER or INT • The INTEGER data type accepts numeric values with an implied scale of zero. It stores any integer value between the range 2^ -31 and 2^31 -1 • Examples INTEGER or INT • Valid • -2147483648 • -1025 • 0 • 1025.98 (digits to the right of the • decimal point are truncated) • 2147483647 Invalid -1,025,234,000,367 1,025,234,000,367
  • 42. DECIMAL [(p[,s])] or DEC [(p[,s])] • The DECIMAL data type accepts numeric values, for which you may define a precision and a scale in the data type declaration. • The precision is an integer that indicates the number of digits that the number will contain. The scale is an integer that indicates the number of these digits that will represent decimal places to the right of the decimal point. • Examples DECIMAL(10,3) • • Valid • 1234567 • 1234567.123 • -1234567 Invalid 12345678 12345678.12 12345678.123 -12345678 -12345678.12 -12345678.123
  • 43. REAL • The REAL data type accepts approximate numeric values, up to a precision of 64. No parameters are required when declaring a REAL data type. If you attempt to assign a value with a precision greater than 64 an error is raised. • Examples • REAL • Valid • -2345 • 0 • 1E-3 • 1.245 • 123456789012345678901234567890 Invalid 123,456,789,012,345,678,901,234,567,890,123
  • 44. DATE • The DATE data type accepts date values. No parameters are required when declaring a DATE data type. Date values should be specified in the form: YYYY-MM-DD. However, PointBase will also accept single digits entries for month and day values. • Examples • DATE • Valid • DATE '1999-01-01' • DATE '2000-2-2' Invalid DATE '1999-13-1' date '2000-2-30' '2000-2-27' date 2000-2-27
  • 45. TIME • The TIME data type accepts time values. No parameters are required when declaring a TIME data type. time values should be specified in the form: HH:MM:SS • Examples • TIME • Valid • TIME '00:00:00' • TIME '1:00:00' • TIME '23:59:59' • time '23:59:59.99' Invalid TIME '00:62:00' TIME '00:3:00' TIME '23:01' '24:01:00'
  • 46. TIMESTAMP • The TIMESTAMP data type accepts timestamp values, which are a combination of a DATE value and a TIME value. • Examples TIMESTAMP • Valid • TIMESTAMP `1999-12-31 23:59:59.99' • TIMESTAMP `2000-01-01 00:00:00' • Invalid • 1999-00-00 00:00:00 • TIMESTAMP `1999-01-01 00:64:00'
  • 50. DDL statements The SQL CREATE DATABASE Statement • The CREATE DATABASE statement is used to create a new SQL database. • CREATE DATABASE databasename; • Exp: • CREATE DATABASE testDB;
  • 51. • Table and Column names should be meaningful and reflect the nature of the data that is to be stored. • If the data stored is about the products that a firm sells , then the table should probably be named product! • If products are identified by a string of eight characters, then the column that stores the product information data should be named product_number, or product_code. Naming Tables and Columns
  • 52. • One of the first steps in creating a database is to create the tables that will store organization’s data. • In order to create a table , four pieces of information must be determined: 1. The table name 2. The column (field) names 3. Column data types and 4. Column sizes Table Creation
  • 53. SQL CREATE TABLE Statement • The CREATE TABLE statement is used to create a new table in a database. • CREATE TABLE table_name ( column1 datatype, column2 datatype, column3 datatype, .... ); • The column parameters specify the names of the columns of the table. The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer, date, etc.).
  • 54. • Exp: • CREATE TABLE Persons ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) );
  • 55. The SQL DROP TABLE Statement • The DROP TABLE statement is used to drop an existing table in a database. • DROP TABLE table_name; • Exp: • DROP TABLE Shippers;
  • 56. SQLALTER TABLE Statement • The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. • The ALTER TABLE statement is also used to add and drop various constraints on an existing table. • ALTER TABLE table_name( ADD column_name datatype);
  • 57. ALTER TABLE - DROP COLUMN • To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column): • ALTER TABLE table_name ( DROP COLUMN column_name);
  • 58. Example: CREATE TABLE FoodCart ( date varchar(10), food varchar(20), profit float ); ALTER TABLE FoodCart ( ADD sold int ); ALTER TABLE FoodCart( DROP COLUMN profit ); DROP TABLE FoodCart; profitfooddate soldprofitfooddate soldfooddate FoodCart FoodCart FoodCart
  • 59. SQL: UPDATE Statement To update the content of the table: UPDATE statement syntax: UPDATE table name SET <attr> = <value> WHERE <selection condition>; Example: UPDATE FoodCart SET sold = 349 WHERE date = ’02/25/08’AND food = ‘pizza’; FoodCart FoodCart (updated) 70pizza02/26/08 500hotdog02/26/08 350pizza02/25/08 soldfooddate 70pizza02/26/08 500hotdog02/26/08 349pizza02/25/08 soldfooddate • Example conditions: – sold < 40 – food = ‘pizza’
  • 60. SQL: DELETE Statement To delete rows from the table: DELETE statement syntax: DELETE FROM <table name> WHERE <condition>; Example: DELETE FROM FoodCart WHERE food = ‘hotdog’; FoodCart FoodCart Note: If the WHERE clause is omitted all rows of data are deleted from the table. 70pizza02/26/08 500hotdog02/26/08 349pizza02/25/08 soldfooddate 70pizza02/26/08 349pizza02/25/08 soldfooddate
  • 61. DML statements The SELECT statement • The SELECT statement is the core of SQL, and it is likely that the vast majority of your SQL commands will be SELECT statements. • The SELECT statement is used to query the database and retrieve selected data that match the criteria that you specify.
  • 62. SQL: SELECT Statement A basic SELECT statement includes 3 clauses SELECT <attribute name> FROM <tables> WHERE <condition> SELECT Specifies the attributes that are part of the resulting relation FROM Specifies the tables that serve as the input to the statement WHERE Specifies the selection condition, including the join condition. Note: that you don't need to use WHERE
  • 63. • SELECT column1, column2, ... FROM table_name WHERE condition; • AND Syntax • SELECT column1, column2, ... FROM table_name WHERE condition1 AND condition2 AND condition3 ...;
  • 64. • OR Syntax • SELECT column1, column2, ... FROM table_name WHERE condition1 OR condition2 OR condition3 ...; • NOT Syntax • SELECT column1, column2, ... FROM table_name WHERE NOT condition;
  • 65. Examples • SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; • SELECT * FROM Customers WHERE City='Berlin' OR City='München'; • SELECT * FROM Customers WHERE NOT Country='Germany';
  • 66. • SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR City='München'); • SELECT * FROM Customers WHERE NOT Country='Germany' AND NOT Country='USA';
  • 67. Using a “*” in a select statement indicates that every attribute of the input table is to be selected. Example: SELECT * FROM … WHERE …; To get unique rows, type the keyword DISTINCT after SELECT. Example: SELECT DISTINCT * FROM … WHERE …; SQL: SELECT Statement (cont.)
  • 68. Example Tables Student ID First Last S103 John Smith S104 Mary Jones S105 Jane Brown S106 Mark Jones S107 John Brown Course Code Title DBS Database Systems PR1 Programming 1 PR2 Programming 2 IAI Intro to AI Grade ID Code Mark S103 DBS 72 S103 IAI 58 S104 PR1 68 S104 IAI 65 S106 PR2 43 S107 PR1 76 S107 PR2 60 S107 IAI 35
  • 69. DISTINCT and ALL • Sometimes you end up with duplicate entries • Using DISTINCT removes duplicates • Using ALL retains them - this is the default SELECT ALL Last FROM Student SELECT DISTINCT Last FROM Student Last Smith Jones Brown Jones Brown Last Smith Jones Brown
  • 70. WHERE Clauses • Usually you don’t want all the rows – A WHERE clause restricts the rows that are returned – It takes the form of a condition - only those rows that satisfy the condition are returned • Example conditions: – Mark < 40 – First = ‘John’ – First <> ‘John’ – First = Last – (First = ‘John’) AND (Last = ‘Smith’) – (Mark < 40) OR (Mark > 70)
  • 71. WHERE Examples SELECT * FROM Grade WHERE Mark >= 60; SELECT DISTINCT ID FROM Grade WHERE Mark >= 60; ID Code Mark S103 DBS 72 S104 PR1 68 S104 IAI 65 S107 PR1 76 S107 PR2 60 ID S103 S104 S107
  • 72. Example: Person 8034Peter 5454Helena 7029George 6428Sally 8034Harry WeightAgeName 8034Peter 5454Helena 8034Harry WeightAgeName 80 54 80 Weight 1) SELECT * FROM person WHERE age > 30; 2) SELECT weight FROM person WHERE age > 30; 3) SELECT distinct weight FROM person WHERE age > 30; 54 80 Weight
  • 73. SQL: The ORDER BY Clause Ordered result selection desc (descending order) SELECT * FROM emp order by state desc; puts state in descending order, e.g. TN, MA, CA asc (ascending order) SELECT * FROM emp order by id asc; puts ID in ascending order, e.g. 1001, 1002, 1003
  • 74. The SQL COUNT(), AVG() and SUM() Functions • The COUNT() function returns the number of rows that matches a specified criteria. • SELECT COUNT(column_name) FROM table_name WHERE condition; • The AVG() function returns the average value of a numeric column. • SELECT AVG(column_name) FROM table_name WHERE condition; • The SUM() function returns the total sum of a numeric column. • SELECT SUM(column_name) FROM table_name WHERE condition;
  • 75. As • Use as to put the output of any operation in new column and specify this name • Example: • SELECT AVG(price) as average; • The average will calculated for the column of name price and put the result in a new coulmn of name average.
  • 76. SQL: The GROUP BY Clause The function to divide the tuples into groups and returns an aggregate for each group. Usually, it is an aggregate function’s companion SELECT food, sum(sold) as totalSold FROM FoodCart group by food; FoodCart 419pizza 500hotdog totalSoldfood 70pizza02/26/08 500hotdog02/26/08 349pizza02/25/08 soldfooddate
  • 77. The SQL MIN() and MAX() Functions • The MIN() function returns the smallest value of the selected column. • SELECT MIN(column_name) FROM table_name WHERE condition; • The MAX() function returns the largest value of the selected column. • SELECT MAX(column_name) FROM table_name WHERE condition;
  • 78. Example • SELECT MAX(Price) AS LargestPrice FROM Products; • SELECT MIN(Price) AS SmallestPrice FROM Products;
  • 79. SELECT from Multiple Tables • Often you need to combine information from two or more tables • You can get the effect of a product by using SELECT * FROM Table1, Table2... • If the tables have columns with the same name ambiguity results • You resolve this by referencing columns with the table name TableName.Column
  • 80. SELECT from Multiple Tables ID First Last ID Code Mark S103 John Smith S103 DBS 72 S103 John Smith S103 IAI 58 S104 Mary Jones S104 PR1 68 S104 Mary Jones S104 IAI 65 S106 Mark Jones S106 PR2 43 S107 John Brown S107 PR1 76 S107 John Brown S107 PR2 60 SELECT ... FROM Student, Grade WHERE (Student.ID = Grade.ID) AND (Mark >= 40); Student ID First Last S103 John Smith S104 Mary Jones S105 Jane Brown S106 Mark Jones S107 John Brown Grade ID Code Mark S103 DBS 72 S103 IAI 58 S104 PR1 68 S104 IAI 65 S106 PR2 43 S107 PR1 76 S107 PR2 60 S107 IAI 35
  • 81. SELECT from Multiple Tables • Suppose you have another table, with name course Find the output of the following statements: SELECT * FROM Student, Grade, Course WHERE Student.ID = Grade.ID AND Course.Code = Grade.Code
  • 82. SELECT from Multiple Tables ID First Last ID Code Mark Code Title S103 John Smith S103 DBS 72 DBS Database Systems S103 John Smith S103 IAI 58 IAI Intro to AI S104 Mary Jones S104 PR1 68 PR1 Programming 1 S104 Mary Jones S104 IAI 65 IAI Intro to AI S106 Mark Jones S106 PR2 43 PR2 Programming 2 S107 John Brown S107 PR1 76 PR1 Programming 1 S107 John Brown S107 PR2 60 PR2 Programming 2 S107 John Brown S107 IAI 35 IAI Intro to AI Student Grade Course Student.ID = Grade.ID Course.Code = Grade.Code SELECT * FROM Student, Grade, Course WHERE Student.ID = Grade.ID AND Course.Code = Grade.Code
  • 83. SQL: Join operation A join (inner join) can be specified in the FROM clause which list the two input relations. Example: Biotech1003 Sales1002 IT1001 DivisionID TN1002 MA1001 CA1000 StateID Emp Dept
  • 84. SQL: Join operation (cont.) Sales1002 IT1001 Dept.DivisionDept.ID TN1002 MA1001 Emp.StateEmp.ID inner join = join SELECT * FROM emp join dept (or FROM emp, dept) ON emp.id = dept.id; Biotech1003 Sales1002 IT1001 DivisionID TN1002 MA1001 CA1000 StateIDEmp Dept
  • 85.
  • 86. INSERT INTO Syntax • The INSERT INTO statement is used to insert new records in a table. • INSERT INTO table_name (column1, column2, column3, ...) • VALUES (value1, value2, value3, ...);
  • 87. Example: INSERT into FoodCart VALUES (’02/26/08', ‘pizza', 70 ); FoodCart 70pizza02/26/08 500hotdog02/26/08 350pizza02/25/08 soldfooddate 500hotdog02/26/08 350pizza02/25/08 soldfooddate
  • 88. Comments • comments start with /* and end with */. • Any text between /* and */ will be ignored. • /*Select all the columns of all the records in the Customers table:*/ SELECT * FROM Customers;
  • 89. SQL Constraints • SQL constraints are used to specify rules for the data in a table. • If there is any violation between the constraint and the data action, the action is aborted. • Constraints can be column level or table level. Column level constraints apply to a column, and table level constraints apply to the whole table. • Examples of constraints: • keys, domain constraints, tuple constraints.
  • 90. SQL contrains • The following constraints are commonly used in SQL: • NOT NULL - Ensures that a column cannot have a NULL value • UNIQUE - Ensures that all values in a column are different • CHECK - Ensures that all values in a column satisfies a specific condition • PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table • FOREIGN KEY - Uniquely identifies a row/record in another table • DEFAULT - Sets a default value for a column when no value is specified
  • 91. SQL NOT NULL Constraint • By default, a column can hold NULL values. • The NOT NULL constraint enforces a column to NOT accept NULL values. • This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.
  • 92. • Exp: • CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255) NOT NULL, Age int );
  • 93. SQL UNIQUE Constraint • The UNIQUE constraint ensures that all values in a column are different. • Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. • A PRIMARY KEY constraint automatically has a UNIQUE constraint. • However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
  • 94. • CREATE TABLE Persons ( ID int NOT NULL UNIQUE, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int );
  • 95. Check or Table Constraints CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, CHECK ( rating >= 1 AND rating <= 10 )); Check constrain keep the values in the attribute rating between 1 and 10
  • 96. SQL PRIMARY KEY Constraint • The PRIMARY KEY constraint uniquely identifies each record in a database table. • Primary keys must contain UNIQUE values, and cannot contain NULL values. • A table can have only one primary key, which may consist of single or multiple fields.
  • 97. • CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, PRIMARY KEY (ID) );
  • 98. SQL PRIMARY KEY on ALTER TABLE • To create a PRIMARY KEY constraint on the "ID" column when the table is already created, use the following SQL: • ALTER TABLE Persons ADD PRIMARY KEY (ID); • ALTER TABLE Persons DROP PRIMARY KEY;
  • 99. SQL FOREIGN KEY CONSTRAINT • The SQL FOREIGN KEY CONSTRAINT is used to ensure the referential integrity of the data in one table to match values in another table. The FOREIGN KEY CONSTRAINT is a column or list of columns which points to the PRIMARY KEY of another table. The main purpose of FOREIGN KEY is, only those values will appear which are present in the primary key table.
  • 100. Field Name Data Type Size Decimal Places NULL Constraint agent_code char 6 No PRIMARY KEY agent_name char 40 No working_area char 35 Yes commission decimal 10 2 Yes phone_no char 17 Yes agents Field Name Data Type Size Decimal Places NULL Constraint cust_code char 6 No PRIMARY KEY cust_name char 25 Yes cust_city char 25 Yes agent_code char 6 Yes FOREIGN KEY customer1
  • 101. Example • SQL Code: • CREATE TABLE customer1( • cust_code char(6) NOT NULL PRIMARY KEY, • cust_name char(25), • cust_city char(25), • agent_code char(6), • FOREIGN KEY(agent_code) • REFERENCES agents (agent_code) ) ;
  • 102. SQL DEFAULT Constraint • The DEFAULT constraint is used to provide a default value for a column. • The default value will be added to all new records IF no other value is specified. CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, City varchar(255) DEFAULT 'Sandnes' );
  • 104. Example: Using Table Constraints
  • 106. 106 Rows describe the Occurrence of an Entity Table Design Name Address Jane Doe 123 Main Street John Smith 456 Second Street Mary Poe 789 Third Ave Columns describe one characteristic of the entity
  • 107. 107 Using SQL To begin, you must first CREATE a database using the following SQL statement: CREATE DATABASE database_name
  • 108. 108 Using SQL • To create a table in the current database, use the CREATE TABLE keyword CREATE TABLE authors (auth_id int(9) not null, auth_name char(40) not null) auth_id auth_name (9 digit int) (40 char string)
  • 109. 109 Data Retrieval (Queries) • Queries search the database, fetch info, and display it. This is done using the keyword SELECT SELECT * FROM publishers pub_id pub_name address state 0736 New Age Books 1 1st Street MA 0987 Binnet & Hardley 2 2nd Street DC 1120 Algodata Infosys 3 3rd Street CA The *Operator asks for every column in the table.
  • 110. 110 Data Retrieval (Queries) • Queries can be more specific with a few more lines pub_id pub_name address state 0736 New Age Books 1 1st Street MA 0987 Binnet & Hardley 2 2nd Street DC 1120 Algodata Infosys 3 3rd Street CA Only publishers in CA are displayed SELECT * from publishers where state = ‘CA’
  • 111. 111 Data Input • Putting data into a table is accomplished using the keyword INSERT pub_id pub_name address state 0736 New Age Books 1 1st Street MA 0987 Binnet & Hardley 2 2nd Street DC 1120 Algodata Infosys 3 3rd Street CA Table is updated with new information INSERT INTO publishers VALUES (‘0010’, ‘pragmatics’, ‘4 4th Ln’, ‘il’) pub_id pub_name address state 0010 Pragmatics 4 4th Ln IL 0736 New Age Books 1 1st Street MA 0987 Binnet & Hardley 2 2nd Street DC 1120 Algodata Infosys 3 3rd Street CA Keyword Variable
  • 112. 112 Using SQL • To insert data in the current table, use the keyword INSERT INTO auth_id auth_name Then issue the statement SELECT * FROM authors INSERT INTO authors values(‘000000001’, ‘John Smith’) 000000001 John Smith
  • 113. 113 Using SQL SELECT auth_name, auth_city FROM publishers auth_id auth_name auth_city auth_state 123456789 Jane Doe Dearborn MI 000000001 John Smith Taylor MI auth_name auth_city Jane Doe Dearborn John Smith Taylor If you only want to display the author’s name and city from the following table:
  • 114. 114 Using SQL DELETE from authors WHERE auth_name=‘John Smith’ auth_id auth_name auth_city auth_state 123456789 Jane Doe Dearborn MI 000000001 John Smith Taylor MI To delete data from a table, use the DELETE statement:
  • 115. 115 Using SQL UPDATE authors SET auth_name=‘hello’ auth_id auth_name auth_city auth_state 123456789 Jane Doe Dearborn MI 000000001 John Smith Taylor MI To Update information in a database use the UPDATE keyword Hello Hello Sets all auth_name fields to hello
  • 116. 116 Using SQL ALTER TABLE authors ADD birth_date datetime null auth_id auth_name auth_city auth_state 123456789 Jane Doe Dearborn MI 000000001 John Smith Taylor MI To change a table in a database use ALTER TABLE. ADD adds a characteristic. ADD puts a new column in the table called birth_date birth_date . .
  • 117. 117 Using SQL ALTER TABLE authors DROP birth_date auth_id auth_name auth_city auth_state 123456789 Jane Doe Dearborn MI 000000001 John Smith Taylor MI To delete a column or row, use the keyword DROP DROP removed the birth_date characteristic from the table auth_state . .
  • 118. 118 Using SQL DROP DATABASE authors auth_id auth_name auth_city auth_state 123456789 Jane Doe Dearborn MI 000000001 John Smith Taylor MI The DROP statement is also used to delete an entire database. DROP removed the database and returned the memory to system
  • 119. SQL examples • CREATE TABLE STATION (ID INTEGER PRIMARY KEY, CITY CHAR(20), STATE CHAR(2), LAT_N REAL, LONG_W REAL); • INSERT INTO STATION VALUES (13, 'Phoenix', 'AZ', 33, 112); INSERT INTO STATION VALUES (44, 'Denver', 'CO', 40, 105); INSERT INTO STATION VALUES (66, 'Caribou', 'ME', 47, 68); • SELECT LAT_N, CITY, TEMP_F FROM STATS, STATION WHERE MONTH = 7 AND STATS.ID = STATION.ID ORDER BY TEMP_F;
  • 120. Compiling between relational algebra& SQL 120
  • 121. 121
  • 123. SQL Statement Syntax AND / OR SELECT column_name(s) FROM table_name WHERE condition AND|OR condition ALTER TABLE ALTER TABLE table_name ADD column_name datatypeor ALTER TABLE table_name DROP COLUMN column_name AS (alias) SELECT column_name AS column_alias FROM table_nameor SELECT column_name FROM table_name AS table_alias CREATE VIEW CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition
  • 124. BETWEEN SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2 CREATE DATABASE CREATE DATABASE database_name CREATE TABLE CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, ... ) CREATE INDEX CREATE INDEX index_name ON table_name (column_name)or CREATE UNIQUE INDEX index_name ON table_name (column_name)
  • 125. DELETE DELETE FROM table_name WHERE some_column=some_valueor DELETE FROM table_name (Note: Deletes the entire table!!) DELETE * FROM table_name (Note: Deletes the entire table!!) DROP DATABASE DROP DATABASE database_name DROP INDEX DROP INDEX table_name.index_name (SQL Server) DROP INDEX index_name ON table_name (MS Access) DROP INDEX index_name (DB2/Oracle) ALTER TABLE table_name DROP INDEX index_name (MySQL)
  • 126. DROP TABLE DROP TABLE table_name EXISTS IF EXISTS (SELECT * FROM table_name WHERE id = ?) BEGIN --do what needs to be done if exists END ELSE BEGIN --do what needs to be done if not END GROUP BY SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value
  • 127. IN SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,..) INSERT INTO INSERT INTO table_name VALUES (value1, value2, value3,....)or INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,....) INNER JOIN SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name LEFT JOIN SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name
  • 128. RIGHT JOIN SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.colum n_name FULL JOIN SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name=table_name2.colum n_name LIKE SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern ORDER BY SELECT column_name(s) FROM table_name ORDER BY column_name [ASC|DESC] SELECT SELECT column_name(s) FROM table_name
  • 129. SELECT * SELECT * FROM table_name SELECT DISTINCT SELECT DISTINCT column_name(s) FROM table_name SELECT INTO SELECT * INTO new_table_name [IN externaldatabase] FROM old_table_nameor SELECT column_name(s) INTO new_table_name [IN externaldatabase] FROM old_table_name SELECT TOP SELECT TOP number|percent column_name(s) FROM table_name TRUNCATE TABLE TRUNCATE TABLE table_name
  • 130. UNION SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2 UNION ALL SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2 UPDATE UPDATE table_name SET column1=value, column2=value,... WHERE some_column=some_value WHERE SELECT column_name(s) FROM table_name WHERE column_name operator value