0% found this document useful (0 votes)
35 views

Chapter 5 Intro To SQL Fall22

This document provides an introduction to the SQL language. It defines SQL as the standard language for storing, manipulating, and retrieving data in a relational database. It explains that SQL is used by all major relational database management systems. The document then discusses some key advantages of SQL, such as allowing users to access, define, and manipulate data. It provides examples of common SQL statements for creating databases and tables, inserting, updating, and deleting data. It also covers specifying constraints and foreign key options when defining tables.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Chapter 5 Intro To SQL Fall22

This document provides an introduction to the SQL language. It defines SQL as the standard language for storing, manipulating, and retrieving data in a relational database. It explains that SQL is used by all major relational database management systems. The document then discusses some key advantages of SQL, such as allowing users to access, define, and manipulate data. It provides examples of common SQL statements for creating databases and tables, inserting, updating, and deleting data. It also covers specifying constraints and foreign key options when defining tables.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Dr Nour Charara

INTRODUCTION TO SQL CSI300


AUCE
1
WHAT IS SQL?

• SQL is Structured Query Language, which is a computer


language for storing, manipulating and retrieving data
stored in a relational database.
• SQL is the standard language for Relational Database
System. All the Relational Database
• Management Systems (RDMS) like MySQL, MS Access,
Oracle, Sybase, Informix, Postgres and SQL Server use SQL
as their standard database language.

2
WHY SQL?
SQL is widely popular because it offers the following advantages:
1. Allows users to access data in the relational database management
systems.
2. Allows users to describe the data.
3. Allows users to define the data in a database and manipulate that
data.
4. Allows to embed within other languages using SQL modules, libraries
&
5. pre-compilers.
6. Allows users to create and drop databases and tables.
7. Allows users to create view, stored procedure, functions in a
database.
8. Allows users to set permissions on tables, procedures and views.
3
4
SQL – CREATE DATABASE

5
SQL ─ DROP OR DELETE DATABASE

6
SQL ─ SELECT DATABASE, USE STATEMENT

7
SQL ─ CREATE TABLE

8
SQL ─ CREATE TABLE
Example

This code block is an example, which creates a CUSTOMERS table with an ID


as a primary key and NOT NULL are the constraints showing that these fields
cannot be NULL while creating records in this table

9
SQL ─ CREATE TABLE

10
SQL - CREATING A TABLE FROM AN EXISTING
TABLE
A copy of an existing table can be created using a combination of
the CREATE TABLE statement and the SELECT statement.

11
SQL - CREATING A TABLE FROM AN EXISTING
TABLE

12
SQL ─ DROP OR DELETE TABLE

Example

13
SQL ─ CREATE TABLE
FULL EXAMPLE THE COMPANY DATABASE
• Figure shows the COMPANY database schema diagram introduced in
previous chapter

14
One possible database state for the COMPANY
relational database schema
CREATE TABLE
The simplest form:

CREATE TABLE DEPARTMENT (


DNAME VARCHAR(15) NOT NULL,
DNUMBER INT NOT NULL,
MGRSSN CHAR(9) NOT NULL,
MGRSTARTDATE DATE );
CREATE TABLE (CONT.)
• CREATE TABLE can also specify the primary key, UNIQUE keys, and
referential integrity constraints (foreign keys)
• Via the PRIMARY KEY, UNIQUE, and FOREIGN KEY phrases

CREATE TABLE DEPARTMENT (


DNAME VARCHAR(15) NOT NULL,
DNUMBER INT NOT NULL,
MGRSSN CHAR(9) NOT NULL,
MGRSTARTDATE DATE,
PRIMARY KEY (DNUMBER),
UNIQUE (DNAME),
FOREIGN KEY(MGRSSN) REFERENCES EMPLOYEE
(SSN));
ALTER TABLE
• Circular reference problem:
– Some foreign keys cause circular references:
• EMPLOYEE.Dno → DEPARTMENT.Dnumber
• DEPARTMENT.Mgr_ssn → EMPLOYEE.Ssn
– One of the tables must be created first without the FOREIGN KEY in the
CREATE TABLE statement
• The missing FOREIGN KEY can be added later using ALTER TABLE , e.g.,
ALTER TABLE DEPARTMENT
ADD CONSTRAINT mgrssn
FOREIGN KEY(Mgr_ssn) REFERENCES EMPLOYEE(ssn) ;
Relational
Schema

Continued next slide…


Relational
Schema
ATTRIBUTE DATA TYPES AND DOMAINS IN SQL
• Basic numeric data types:
– Integers: INTEGER or INT (4 bytes), SMALLINT (2 bytes)
– Real (floating-point): FLOAT or REAL (4 bytes), DOUBLE PRECISION (8
bytes)
– Formatted (fixed-point): DECIMAL(i,j) or DEC (i,j) or NUMERIC(i,j)
specify i (called precision) total decimal digits, j (called scale) after
decimal point
• Basic character string data types:
– Fixed-length: CHAR(n) or CHARACTER(n)
– Variable-length: VARCHAR(n) or CHAR VARYING(n) or CHARACTER
VARYING(n)
ATTRIBUTE DATA TYPES AND DOMAINS IN SQL
(CONT’D.)
Bit-string data types
 Fixed length: BIT(n)
 Varying length: BIT VARYING(n)
Boolean data type
 Values of TRUE or FALSE or NULL
DATE data type
 Ten positions
 Components are YEAR, MONTH, and DAY in the form YYYY-MM-DD
 Multiple mapping functions available in RDBMSs to change date
formats
ATTRIBUTE DATA TYPES AND DOMAINS IN SQL
(CONT’D.)
Timestamp data type
Includes the DATE and TIME fields
 Plus a minimum of six positions for decimal fractions of seconds
 Optional WITH TIME ZONE qualifier
INTERVAL data type
 An interval is defined as the difference between two dates and
times. Intervals are expressed in one of two different ways. One is a
year-month interval that expresses intervals in terms of years and an
integral number of months.
DATE, TIME, Timestamp, INTERVAL data types can be cast
or converted to string formats for comparison.
ATTRIBUTE DATA TYPES AND DOMAINS IN SQL (CONT’D.)
Domain
 Name used with the attribute specification
 Makes it easier to change the data type for a domain that is used by
numerous attributes
 Improves schema readability
 Example:
 CREATE DOMAIN SSN_TYPE AS CHAR(9);

TYPE
 User Defined Types (UDTs) are supported for object-oriented
applications. Uses the command: CREATE TYPE
SPECIFYING FOREIGN KEY OPTIONS AND NAMING
OF CONSTRAINTS
• We can specify RESTRICT (the default), CASCADE, SET NULL or SET
DEFAULT on referential integrity constraints (foreign keys)
• Separate options for ON DELETE, ON UPDATE
• ON DELETE SET DEFAULT SQL Server sets the rows in the child table to their default
values if the corresponding rows in the parent table are deleted.
• ON UPDATE CASCADE / ON DELETE CASCADE A foreign key with cascade delete means
that if a record in the parent table is updated or deleted, then the corresponding records in
the child table will automatically be deleted
• Figure (next slide) gives some examples
• A constraint can be given a constraint name; this allows to DROP the
constraint later
• Figure (next slide) illustrates naming of constraints
Relational
Schema
SQL ─ INSERT QUERY

29
OPERATIONS TO MODIFY RELATIONS
• Three basic operations:
– INSERT
– DELETE
– UPDATE
SQL STATEMENTS FOR UPDATING THE DATABASE

• There are three SQL commands to modify the database:


INSERT, DELETE, and UPDATE
• INSERT is used for adding one or more records to a table
• DELETE is for removing records
• UPDATE is for modifying existing records
• Some operations may be rejected if they violate integrity
constraints; others may propagate additional updating
automatically if specified in the database schema
INSERT STATEMENT
• Used to add one or more tuples (records) to a relation
(table)
• Values for the attributes should be listed in the same order
as the attributes were specified in the CREATE TABLE
command

• Attributes that have defaults values can be omitted in the


new record(s)
INSERT STATEMENT (CONT.)
• Example:
U1:INSERT INTO EMPLOYEE
VALUES ('Richard’, 'K’, 'Marini’, '653298653’, '30-DEC-52',
'98 Oak Forest,Katy,TX', 'M', 37000,'987654321', 4 ) ;

• An alternate form of INSERT specifies explicitly the attribute


names that correspond to the values in the new tuple
– Attributes with NULL or default values can be left out

• Example: Insert a tuple for a new EMPLOYEE for whom we


only know the FNAME, LNAME, and SSN attributes.
U1A: INSERT INTO EMPLOYEE (FNAME, LNAME, SSN)
VALUES ('Richard', 'Marini', '653298653') ;
DELETE STATEMENT
• Removes tuples from a relation
– Includes a WHERE-clause to select the tuples to be deleted
– Referential integrity should be enforced (via REJECT/RESTRICT,
CASCADE, SET NULL, or SET DEFAULT)
– Tuples are deleted from only one table at a time (unless CASCADE is
specified on a referential integrity constraint)
– Missing WHERE-clause deletes all tuples in the relation; the table then
becomes an empty table
– Number of tuples deleted is the number of tuples selected by the
WHERE-clause
DELETE STATEMENT (CONT.)
• Examples:
U4A: DELETE FROM EMPLOYEE
WHERE LNAME='Brown' ;

U4B: DELETE FROM EMPLOYEE


WHERE SSN='123456789’ ;

U4C: DELETE FROM EMPLOYEE


WHERE DNO = 5 ;

U4D: DELETE FROM EMPLOYEE ;


UPDATE STATEMENT
• Used to modify attribute values of one or more selected tuples
• A WHERE-clause selects the tuples to be modified
• An additional SET-clause specifies the attributes to be modified
and their new values
• Each command modifies tuples in the same relation
• Referential integrity should be enforced (via REJECT/RESTRICT,
CASCADE, SET NULL, or SET DEFAULT)
UPDATE STATEMENT (CONT.)
• Example: Change the location and controlling department number of
project number 10 to 'Bellaire' and 5, respectively.
U5:UPDATE PROJECT
SET PLOCATION = 'Bellaire', DNUM = 5
WHERE PNUMBER=10 ;
UPDATE STATEMENT (CONT.)
• Example: Give all employees in department number 5 a 10% raise
in salary
U6: UPDATE EMPLOYEE
SET SALARY = SALARY *1.1
WHERE DNO = 5 ;

• In this request, the modified SALARY value depends on the original


SALARY value in each tuple
– The reference to the SALARY attribute on the right of = refers to the old
SALARY value before modification
– The reference to the SALARY attribute on the left of = refers to the new
SALARY value after modification
INSERTING DATA INTO TABLES WITH
REFERENTIAL CONSTRAINTS
When you insert data into tables with referential constraints, you need to
consider these rules.
If you are inserting data into a parent table with a parent key, SQL does not
allow:
1-Duplicate values for the parent key
2- If the parent key is a primary key, a null value for any column of the
primary key

42
INSERTING DATA INTO TABLES WITH
REFERENTIAL CONSTRAINTS
If you are inserting data into a dependent table with foreign keys:
1- Each non-null value you insert into a foreign key column must be equal to
some value in the corresponding parent key of the parent table.
2- If any column in the foreign key is null, the entire foreign key is considered
null. If all foreign keys that contain the column are null, the INSERT succeeds
(as long as there are no unique index violations).

43
Ssn Dnumber Emp_start_date
Ssn Dnumber Emp_start_date
UPDATED COMPANY relational database schema
SQL ─ SELECT QUERY

48
SQL ─ SELECT QUERY

49
SQL ─ SELECT QUERY

50
NORTHWIND DATABASE - PRACTICING
SELECTING SPECIFIC COLUMNS

/*
Select the FirstName and LastName
columns from the Employees table.
*/
SELECT FirstName, LastName
FROM Employees;

51
NORTHWIND DATABASE - PRACTICING
SELECTING SPECIFIC COLUMNS
Duration: 5 to 15 minutes.
In this exercise, you will practice selecting specific columns from tables in the Northwind
database.

1. Select CategoryName and Description from the Categories table.


2. Select ContactName, CompanyName, ContactTitle and Phone from the Customers table.
3. Select EmployeeID, Title, FirstName, LastName, and Region from the Employees table.
4. Select RegionID and RegionDescription from the Region table.
5. Select CompanyName, Fax, Phone and HomePage from the Suppliers table.

52
NORTHWIND
Solution:
DATABASE - PRACTICING
SELECTING SPECIFIC COLUMNS
SELECT CategoryName, Description
FROM Categories;

SELECT ContactName, CompanyName, ContactTitle, Phone


FROM Customers;

SELECT EmployeeID, Title, FirstName, LastName, Region


FROM Employees;

SELECT RegionID, RegionDescription


FROM Region;

SELECT CompanyName, Fax, Phone, HomePage


FROM Suppliers;
53
SQL ─ ALIAS SYNTAX
You can rename a table or a column temporarily by giving another name known as Alias.

Alias for Columns Examples


The following SQL statement creates two aliases, one for the CustomerID column and one
for the CustomerName column:
Example
SELECT CustomerID AS ID, ContactName AS Customer
FROM Customers;

54
SQL ─ ALIAS SYNTAX
Note: It requires double quotation marks or square brackets if the alias
name contains spaces:

Example
SELECT CustomerName AS Customer, ContactName AS “Contact Person”
FROM Customers;

55
SQL ─ ALIAS SYNTAX – COMBINE COLUMNS
The following SQL statement creates an alias named “Full_Name" that combines two columns
(FirstName and LastName) in one displayed column:

56
SQL ─ ALIAS SYNTAX
The following SQL statement creates an alias named "Address" that combine four columns
(Address, PostalCode, City and Country):

Example
SELECT CONCAT(ContactName, Address , “ “, PostalCode, “ , ”, City, Country) AS Address
FROM Customers;

Select *

57
THE SQL SELECT LIMIT

The SELECT LIMIT clause is used to specify the number of records to return.

58
SQL ─ WHERE CLAUSE
The SQL WHERE clause is used to specify a condition while fetching the data
from a single table or by joining with multiple tables. If the given condition is
satisfied, then only it returns a specific value from the table.
The WHERE clause is not only used in the SELECT statement, but it is also
used in the UPDATE, DELETE statement, etc.

59
SQL ─ WHERE CLAUSE
Example:

60
SQL – OPERATORS
An operator is a reserved word or a character used primarily in an SQL
statement's WHERE clause to perform operation(s)
Comparison operators
Arithmetic operators
Logical operators
Operators used to negate conditions

61
SQL COMPARISON OPERATORS
Assume ‘variable a’ holds 10 and ‘variable b’ holds 20, then:

62
SQL COMPARISON OPERATORS

63
NORTHWIND DATABASE - PRACTICING
THE WHERE CLAUSE AND OPERATOR SYMBOLS
- CHECKING FOR EQUALITY

/*
Create a report showing the title and the first and
last name
of all sales representatives.
*/

SELECT Title, FirstName, LastName


FROM Employees
WHERE Title = 'Sales Representative';

64
NORTHWIND DATABASE - PRACTICING
CHECKING FOR INEQUALITY
/*
Create a report showing the first and last name of
all employees
excluding sales representatives.
*/

SELECT FirstName, LastName


FROM Employees
WHERE Title <> 'Sales Representative';

65
NORTHWIND DATABASE - PRACTICING
CHECKING FOR GREATER OR LESS THAN
/*
Create a report showing the first and last name of
all employees whose last names start with a letter
in the last half of the alphabet.
*/

SELECT FirstName, LastName


FROM Employees
WHERE LastName >= 'N';

66
THE AND OPERATOR

67
NORTHWIND DATABASE - PRACTICING
THE AND OPERATOR
/*
Create a report showing the first and last name of all
sales representatives whose title of courtesy is "Mr.".
*/

SELECT FirstName, LastName


FROM Employees
WHERE Title = 'Sales Representative' AND TitleOfCourtesy = 'Mr.';

68
THE OR OPERATOR

69
THE OR OPERATOR
/*
Create a report showing the first and last name and the city of all
employees who are from Seattle or Redmond.
*/

SELECT FirstName, LastName, City


FROM Employees
WHERE City = 'Seattle' OR City = 'Redmond';

70
ORDER OF EVALUATION
By default, SQL processes AND operators before it processes OR operators. To illustrate
how this works, take a look at the following example.
/*
Create a report showing the first and last name of all sales
representatives who are from Seattle or Redmond.
*/

SELECT FirstName, LastName, City, Title


FROM Employees
WHERE (City = 'Seattle' OR City = 'Redmond‘)
AND Title = 'Sales Representative';

71
WRITING SELECTS WITH MULTIPLE
CONDITIONS
In this exercise, you will practice writing SELECT statements that filter records
based on multiple conditions.

1. Create a report that shows the first and last names and cities of
employees from cities other than Seattle in the state of Washington.
2. Create a report that shows the company name, contact title, city and
country of all customers in Mexico or in any city in Spain except Madrid.

72
SOLUTION
SELECT FirstName, LastName, City
FROM Employees
WHERE Region = 'WA' AND City <> 'Seattle';

SELECT CompanyName, ContactTitle, City, Country


FROM Customers
WHERE Country = 'Mexico' OR (Country = 'Spain'
AND City <> 'Madrid');

73
SQL MIN() AND MAX() FUNCTIONS

The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.

Example
SELECT MAX(UnitPrice) AS LargestPrice
FROM Products;
74
SQL COUNT(), AVG() AND SUM() FUNCTIONS

The COUNT() function returns the number of rows that matches a specified
criteria.
The AVG() function returns the average value of a numeric column.
The SUM() function returns the total sum of a numeric column.

75
SQL COUNT(), AVG() AND SUM() FUNCTIONS
count() Example
The following SQL statement finds the number of products:
SELECT count(ProductID)
FROM Products;
avg() Example
The following SQL statement finds the average price of all
products:
SELECT avg(UnitPrice)
FROM Products;
sum() Example
The following SQL statement finds the sum of the "Quantity"
fields in the "OrderDetails" table:
SELECT sum(Quantity)
FROM OrderDetails;
76
NORTHWIND DATABASE - PRACTICING
CHECKING FOR NULL
/*
Create a report showing the first and last names of
all
employees who have a region specified.
*/

SELECT FirstName, LastName


FROM Employees
WHERE Region IS NOT NULL;

77
NORTHWIND DATABASE - PRACTICING
CHECKING FOR NULL
/*
Create a report showing the first and last names of
all employees whose region is unspecified.
*/

SELECT FirstName, LastName


FROM Employees
WHERE Region IS NULL;

78
NORTHWIND DATABASE - PRACTICING
WHERE AND ORDER BY
/*
Create a report showing the first and last name of all employees
whose
last names start with a letter in the last half of the alphabet.
Sort by LastName in descending order.
*/

SELECT FirstName, LastName


FROM Employees
WHERE LastName >= 'N'
ORDER BY LastName DESC;

79
SQL LIKE OPERATOR

The LIKE operator is used in a WHERE clause to search for a specified


pattern in a column.
There are two wildcards used in conjunction with the LIKE operator:
% The percent sign represents zero, one, or multiple characters
_ The underscore represents a single character
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;

80
SQL LIKE OPERATOR

81
SQL LIKE OPERATOR
Example: selects all customers with a CustomerName starting with "a":
SELECT * FROM Customers
WHERE ContactName LIKE ‘a%’;

Example: selects all customers with a CustomerName ending with "a":


SELECT * FROM Customers
WHERE ContactName LIKE '%a’;

Example: selects all customers with a CustomerName that have "or" in any position:
SELECT * FROM Customers
WHERE ContactName LIKE '%or%';

82
SQL LIKE OPERATOR
Example: selects all customers with a CustomerName that have "r" in the second position:
SELECT * FROM Customers
WHERE ContactName LIKE '_r%';

Example: selects all customers with a CustomerName that starts with "a" and are at least 3
characters in length:
SELECT * FROM Customers
WHERE ContactName LIKE 'a_%_%';

Example: selects all customers with a ContactName that starts with "a" and ends with "o":
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
83
SQL UPDATE STATEMENT
The UPDATE statement is used to modify the existing records in a table.

The following SQL statement updates the first customer (CustomerID = 1)


with a new contact person and a new city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
84
UPDATE MULTIPLE RECORDS

It is the WHERE clause that determines how many records that will be
updated.
The following SQL statement will update the contactname to "Juan" for all
records where country is "Mexico":
Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';

85
SQL DELETE
The DELETE statement is used to delete existing records in a table.

Example
The following SQL statement deletes the customer "Alfreds Futterkiste" from
the "Customers" table:
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

86
SQL DELETE
Delete All Records
It is possible to delete all rows in a table without deleting the table. This
means that the table structure, attributes, and indexes will be intact:
DELETE FROM table_name;
The following SQL statement deletes all rows in the "Customers" table,
without deleting the table:
Example
DELETE FROM Customers;

87

You might also like