You are on page 1of 77

Chapter 4

Structured Query Language (SQL)


2

4.1 Structured Query Language (SQL)


4.1.1 Basic command and functions of SQL
4.1.2 Data types and constraints of SQL
4.1.3 SQL table structure

Database Systems, 9th Edition


Introduction to SQL
3

 Ideally, a database language should allow a user to:


 create the database and relation structures;
perform basic data management tasks, such as the insertion,
modification, and deletion of data from the relations;
 perform both simple and complex queries.
 SQL functions fit into two broad categories:
 Data definition language

 Data manipulation language

 Basic command set has vocabulary of fewer than 100 words


 American National Standards Institute (ANSI) prescribes a standard
SQL
 Several SQL dialects exist
4

Database Systems, 9th Edition


SQL Data types
5

 Data type selection is usually dictated by nature of


data and by intended use

Database Systems, 9th Edition


SQL Constraints
6

 SQL constraints are used to specify rules for the data in a table.
 Constraints are used to limit the type of data that can go into a table. This ensures
the accuracy and reliability of the data in the 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.
 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
 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
 CHECK - Ensures that all values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column when no value is specified
 INDEX - Used to create and retrieve data from the database very quickly
SQL table structure
7

 A table is a collection of related data held in a table format within


a database. It consists of columns, and rows
 CREATE TABLE Syntax:

 Example

Database Systems, 9th Edition


8

 Features:
 The NOT NULL specifications for the attributes ensure that a data entry
will be made.
 The UNIQUE specification creates a unique index in the respective attribute.
Use it to avoid duplicated values in a column.
 The primary key attributes contain both a NOT NULL and a UNIQUE
specification.
 RDBMS will automatically enforce referential integrity for foreign keys
 The entire table definition is enclosed in parentheses. A comma is used to
separate each table element (attributes, primary key, and foreign key)
definition.
 The command sequence ends with a semicolon
9

 Use one line per column (attribute) definition


 Use spaces to line up attribute characteristics

and constraints
 Table and attribute names are capitalized
SQL data definition commands
10

1. Create table
 used to specify a new relation by giving it a name

 and specifying its attributes and initial constraints. The


attributes are specified first,
 and each attribute is given a name, a data type to
specify its domain of values, and
 any attribute constraints, such as NOT NULL. The key,
entity integrity, and referential
 integrity constraints can be specified within the CREATE
TABLE statement after
 the attributes are declared

Database Systems, 9th Edition


11

 CREATE TABLE Syntax:

 Example

Database Systems, 9th Edition


Advanced Data Definition Commands
12

2. Alter table
 All changes in table structure are made by using ALTER
command
 Three options:

 ADD adds a column


 MODIFY changes column characteristics
 DROP deletes a column

 Can also be used to:


 Add table constraints
 Remove table constraints

Database Systems, 9th Edition


13

Database Systems, 9th Edition


Adding a Column
Dropping a Column
14

 Use ALTER to add column


 Do not include the NOT NULL clause for new column
 Use ALTER to drop column
 Some RDBMSs impose restrictions on the deletion of an
attribute
Changing a Column’s Data Type
15

 ALTER can be used to change data type


 Some RDBMSs do not permit changes to data types
unless column is empty

Database Systems, 9th Edition


Changing a Column’s Data
16
Characteristics
 Use ALTER to change data characteristics
 Changes in column’s characteristics are permitted if
changes do not alter the existing data type
 For example, if you want to increase the width of
the Test column to nine digits, use the command:

ALTER TABLE STAFF


MODIFY (Test Numeric (9,2));

Database Systems, 9th Edition


17

3. Drop table
A table can be deleted from the database using the
DROP TABLE command

 Example

Database Systems, 9th Edition


Data Manipulation Commands
18

A. INSERT
B. SELECT
C. ORDER BY
D. GROUP BY
E. HAVING
F. WHERE
G. UPDATE
H. DELETE
I. COMMIT
J. ROLLBACK

Database Systems, 9th Edition


Data Manipulation Commands
19

 INSERT
 SELECT

 COMMIT
 UPDATE
 ROLLBACK
 DELETE

Database Systems, 9th Edition


INSERT
20

 INSERT
 Used to enter data into table
 Syntax:
 INSERTINTO columnname
VALUES (value1, value2, … , valueN);

Database Systems, 9th Edition


21

 When entering values, notice that:


 Row contents are entered between parentheses
 Character and date values are entered between
apostrophes
 Numerical entries are not enclosed in apostrophes

 Attribute entries are separated by commas

 A value is required for each column

 Use NULL for unknown values

Database Systems, 9th Edition


22

 Example

Database Systems, 9th Edition


SELECT
23

 SELECT
 Syntax:

Database Systems, 9th Edition


24

 SELECTING ALL COLUMNS

Database Systems, 9th Edition


25

 SELECTING SPECIFIC COLUMNS

Database Systems, 9th Edition


26

 USING ALIASES

Database Systems, 9th Edition


27

 USING ARITHMETIC OPERATORS (*, / , +, -)

Database Systems, 9th Edition


28

 USING PARENTHESES

Database Systems, 9th Edition


29

 ELIMINATE DUPLICATE ROWS

Database Systems, 9th Edition


ORDER BY
30

 Specifies an order for displaying the result of a


query.
 Syntax:
Original table

 Example
Group By
31

 Specifies the grouping attributes.


 Generally used when you have attribute columns
combined with aggregate functions in the SELECT
statement.
 Syntax:

 The GROUP BY clause is valid only when used in


conjunction with one of the SQL aggregate functions,
such as COUNT, MIN, MAX, AVG, and SUM
Database Systems, 9th Edition
32

 Examples

NVL FUNCTION
FORCES GROUP
FUNCTION TO INCLUDE
NULL VALUES

 GROUP BY Column Does Not Have To Be In The Select List


33

 GROUP MULTIPLE COLUMNS


 Example

Database Systems, 9th Edition


HAVING
34

 A particularly useful extension of the GROUP BY


feature is the HAVING clause. The HAVING
operates very much
 like the WHERE clause in the SELECT statement.
However, the WHERE clause applies to columns and
expressions for individual rows, while the HAVING
clause is applied to the output of a GROUP BY
operation.

Database Systems, 9th Edition


35

 Example:

Database Systems, 9th Edition


WHERE
36

 WHERE clause to add conditional restrictions to the


SELECT statement.
 Syntax:

 Example:

Database Systems, 9th Edition


Update
37

 Modify data in a table


 Syntax:

 If more than one attribute is to be updated in row,


separate corrections with commas
 Example
Delete
38

 Delete a table row.


 Syntax:

 Example
Commit
39

 Changes made to table contents are not physically


saved on disk until:
 Database is closed
 Program is closed

 COMMIT command is used

 Syntax:
 COMMIT [WORK];
 Will permanently save any changes made to any
table in the database
MySQL:
Autocommit
Rollback
40

 ROLLBACK
 Undoes changes since last COMMIT
 Brings data back to prechange values

 Syntax:
 ROLLBACK;

 COMMIT and ROLLBACK only work with commands


to add, modify, or delete table rows

Database Systems, 9th Edition


Rules of Precedence
41

Database Systems, 9th Edition


Comparison operators
42

 Comparison operators may even be used to place


restrictions on character-based attributes

 Example:
Arithmetic Operators:
43
The Rule of Precedence
 Perform operations within parentheses
 Perform power operations
 Perform multiplications and divisions
 Perform additions and subtractions

Database Systems, 9th Edition


44

 Examples:

Database Systems, 9th Edition


Logical Operators: AND, OR, and NOT
45

 Searching data involves multiple conditions


 Logical operators: AND, OR, and NOT
 Can be combined
 Parentheses enforce precedence order
 Conditions in parentheses are always executed first
 Boolean algebra: mathematical field dedicated to
use of logical operators
 NOT negates result of conditional expression

Database Systems, 9th Edition


46

Database Systems, 9th Edition


Special Operators
47

 BETWEEN: checks whether attribute value is within


a range
 IS NULL: checks whether attribute value is null
 LIKE: checks whether attribute value matches given
string pattern
 IN: checks whether attribute value matches any
value within a value list
 EXISTS: checks if subquery returns any rows

Database Systems, 9th Edition


BETWEEN
48

Database Systems, 9th Edition


IS NULL
49

Database Systems, 9th Edition


LIKE
50

Database Systems, 9th Edition


IN
51

Database Systems, 9th Edition


EXISTS
52

 Used to check whether a subquery returns any rows.


 Syntax:

Database Systems, 9th Edition


53

 Example
54

Database Systems, 9th Edition


Aggregate Functions
55

Database Systems, 9th Edition


56

Database Systems, 9th Edition


4.3 Analyze SQL Server /Open source
57
Software
 Database Open source softwares
 Example

Database Systems, 9th Edition


Airtable
58

 Airtable is cloud-based database software that comes with features such as data
tables for capturing and displaying information, user permissions for managing the
database, and file storage and sharing capabilities with document history tracking.
 The tool can also be used to manage and track tasks using its kanban dashboards,
built-in calendars, and spreadsheets.
Pros: Users mention that the tool is
easy to get started with due to its
pre-built database templates for
different business purposes, such as
lead management, bug tracking, and
applicant tracking.

Cons: Users mention that the tool


offers limited relational database
functionality, making it difficult to link
records residing in multiple tables.
GraphDB
59

 GraphDB is a graphical database that comes with both cloud and on-premise
deployment options. It offers features such as data repositories, textual analytics,
and knowledge graphs.
 The tool can be used to tag and analyze textual data semantically based on
keywords and topics or concepts. The tagged data can then be visualized as
knowledge graphs to search and find relationships between disparate data.

Pros: Users mention that


the tool is easy to setup
and has a user-friendly
interface that is simple for
novice users to get started
with.

Cons: Users mention that


the tools slow down when
importing large files.
MariaDB
60

 MariaDB is an open source relational database for data storage, data insertion into
tables, data modifications, and data retrieval. As an open source solution, the tool is
free to use and you can get started by downloading the software on your desktop
or laptop.

Pros: Users mention that


MariaDB’s open source
community consist of
active members who roll
out patches and updates
regularly.

Cons: Users mention that


the tool lacks a graphical
user interface and users
can operate the tool only
by using the command
line.
PostgreSQL
61

 PostgreSQL is an open source database that comes with features such as data
indexing, user configuration settings, data import/export, and version control.
 While PostgreSQL is a relational database, it also allows creating NoSQL
databases with programming languages such as Python and JSON.

Pros: Users mention that


the tool has a large open
source community that has
built several plugins for the
tool, improving its
functionality.

Cons: Users mention that it


takes a long time to install
and configure the solution.
QuintaDB
62

 QuintaDB is a cloud-based relational database that comes with features such as a


form builder, user permission settings, data import/export, team calendars, and
email/SMS notifications.
 QuintaDB’s free version allows for creating forms (up to 5) and records in the
database (up to 1,000), and sharing/storing files (up to 500MB).

Pros: Users mention that the tool


offers flexibility in setting up user
permissions, allowing them to
collaboratively use the database
with multiple members with
different levels of access rights.

Cons: Users mention that the tool


offers limited pre-built database
templates and web forms—it takes
them time to custom design tables
using their own CSS.
Sonadier
63

 Sonadier is cloud-based solution for creating databases and web forms. The tool
comes with features such as form generation through a drag-and-drop interface,
file management, user data sharing permissions, data import/export, and data
versioning.

Pros: Users like the clean


interface of the solution,
which makes creating
databases and forms quick
and simple.

Cons: Users mention that


the customer support takes
a long time to respond to
requests for bug fixes.
MySQL
64

 This is one of the most popular relational database systems. Originally an open-
source solution, MySQL now is owned by Oracle Corporation. Today, MySQL is a
pillar of LAMP application software. That means it’s a part of Linux, Apache,
MySQL, and Perl/PHP/Python stack. Having C and C++ under the hood, MySQL
works well with such system platforms as Windows, Linux, MacOS, IRIX, and others.

Pros of MySQL
Free installation.
Simple syntax and mild
complexity.
Cloud-compatible.

Cons of MySQL
Scalability challenges.
Partial open source.
Limited compliance with SQL
standards.
Joining Database Tables
65

 Joining tables is the most important distinction


between relational database and other DBs
 Join is performed when data are retrieved from
more than one table at a time
 Equality comparison between foreign key and primary
key of related tables
 Join tables by listing tables in FROM clause of
SELECT statement
 DBMS creates Cartesian product of every table

Database Systems, 9th Edition


Joining Tables with an Alias
66

 Alias identifies the source table from which data


are taken
 Alias can be used to identify source table
 Any legal table name can be used as alias
 Add alias after table name in FROM clause
 FROM tablename alias

Database Systems, 9th Edition


Recursive Joins
67
Outer Joins
 Alias is especially useful when a table must be
joined to itself
 Recursive query
 Use aliases to differentiate the table from itself

 Two types of outer join


 Leftouter join
 Right outer join

Database Systems, 9th Edition


68

Database Systems, 9th Edition


69

Database Systems, 9th Edition


70

 Example:
STAFF

Database Systems, 9th Edition


71

Database Systems, 9th Edition


72
73

Database Systems, 9th Edition


74
75

Database Systems, 9th Edition


76

Database Systems, 9th Edition


77

You might also like