0% found this document useful (0 votes)
13 views42 pages

IE 171 Lecture 7 - SQL (Part 1)

The document provides an introduction to Structured Query Language (SQL), covering its components such as Data Manipulation Language (DML) and Data Definition Language (DDL). It explains the purpose of SQL, the use of DBMS software, and includes examples of SQL commands for creating and manipulating database schemas. Additionally, it discusses data types, constraints, and relationships between tables in a relational database context.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views42 pages

IE 171 Lecture 7 - SQL (Part 1)

The document provides an introduction to Structured Query Language (SQL), covering its components such as Data Manipulation Language (DML) and Data Definition Language (DDL). It explains the purpose of SQL, the use of DBMS software, and includes examples of SQL commands for creating and manipulating database schemas. Additionally, it discusses data types, constraints, and relationships between tables in a relational database context.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Structured

Query
Language (SQL)
IE 171: INFORMATION SYSTEMS 1

P RE P ARE D B Y C A S O N DAY

04/18/2023 1
Outline
► Introduction to SQL
◦ DML
◦ DDL

► Why SQL?
► Writing SQL Commands
DBMS Software
Definition: Software that controls the organization,
storage, retrieval, security and integrity of data in a
database.
It accepts requests from the application and instructs the
operating system to transfer the appropriate data.
DBMS Software
Commercial software
◦ Sybase Adaptive Server Enterprise
◦ IBM DB2
◦ Oracle
◦ Microsoft SQL Server
◦ Teradata

Free/GPL/Opensource:
◦ MySQL
◦ PostgreSQL
SQL
The definition of a relational system, requires that
a single language – sometimes called a
comprehensive data sublanguage – be able to
handle all communications with the database.
This language is SQL: Structure Query Language
SQL: pronounced si-kwel or S-Q-L?
A HUGE debate among practitioners
Bill Gates says si-kwel though

6 PREPARED BY CASONDAY
DML and DDL
DML (data manipulation language) – Adds rows, chooses columns to
show
◦ INSERT, UPDATE, SELECT

DDL (data definition language) – Manipulates tables and attributes


◦ CREATE tables, schemas, views
◦ ALTER tables, schemas, views
◦ Link Tables Through Foreign Keys
◦ DROP or Truncate Tables
Why SQL?
Common Language
◦ DBAs, systems programmers, application programmers, systems
analysts, systems designers, and end users
◦ CREATE TABLE Staff(staffNo VARCHAR(5),
lName VARCHAR(15),
salary DECIMAL(7,2));
◦ INSERT INTO Staff VALUES (‘SG16’, ‘Brown’, 8300);
◦ SELECT staffNo, lName, salary
FROM Staff
WHERE salary > 10000;

English-like syntax
Based on Relational Algebra & Relational Calculus
Data Definition
Language (DDL)
BUILDING A SCHEMA ON POSTGRESQL VIA
SQL

04/18/2023 PREPARED BY CASONDAY 9


Let’s Start
Setup a new database for the following examples. Name it
ddl_practice

10 PREPARED BY CASONDAY
Let’s Start
Open the Query Tool to have a canvas on where to write your code.

11 PREPARED BY CASONDAY
Let’s Start
Open the Query Tool to have a canvas on where to write your code.

12 PREPARED BY CASONDAY
Running a code in pgAdmin
Type SELECT version(); into your Query Editor.
Run the script by pressing F5 or clicking on the play button above the
editor.

13 PREPARED BY CASONDAY
Writing SQL Commands
SQL statement consists of reserved words and user-
defined words.
Reserved words are a fixed part of SQL and must be spelt
exactly as required and cannot be split across lines.
User-defined words are made up by user and represent
names of various database objects such as relations,
columns, views.
CREATE TABLE Staff(staffNo VARCHAR(5),
lName VARCHAR(15),
salary DECIMAL(7,2));
Understanding Notations
Use extended form of BNF (Backus Naur Form) notation:

- UPPER-CASE letters represent reserved words.


- LOWER-CASE letters represent user-defined words.
- | indicates a choice among alternatives. (a|b|c)
- Curly braces indicate a required element. {a}
- Square brackets indicate an optional element. [a]
- an ellipsis (…) indicates optional repetition (0 or more).

Example: {a | b} (, c…)

CREATE TABLE TableName [ (columnName datatype [constraints]) ]


Notes on Scripting on Query Tool
1. Terminating a single command with a semicolon (;) is optional
1. The semicolon becomes useful if you want to execute several
commands at once.

2. For now, think of SQL commands as non-case sensitive, but it’s


good practice to maintain a convention of having SQL
commands in BLOCK LETTERS for readability purposes.

16 PREPARED BY CASONDAY
DDL Schema
Schema Definition
◦ is a structure of a particular database described using standard SQL Code

Best Interpretation:
◦ Schema: House Design Plan
◦ Database: House
◦ Table: Kitchen
Building a Schema
For the next slides, feel free to try the following blocks of code into
your pgAdmin on the database ddl_practice

You may Generate ERD for the database from time to time to check
on the changes on the schema

18 PREPARED BY CASONDAY
Let us build this simple schema

19 PREPARED BY CASONDAY
Building your Schema
Create new tables first.
CREATE TABLE TableName [ (columnName datatype [constraints]) ]
The serial datatype is used for id
numbers that automatically
increment with new data
instances

Constraints were also used


• PRIMARY KEY – designates a
primary key
• NOT NULL – prevents the
database to accept data
objects with NULL values for the
column
• DEFAULT – sets the value of an
attribute when no value was
given for a data object
Building your Schema
Create new tables first.
CREATE TABLE TableName [ (columnName datatype) ]

Constraints were used


• UNIQUE – the database will
reject data objects if the
attribute value is already in the
database
Building your Schema
Create new tables first.
CREATE TABLE TableName [ (columnName datatype) ]

This is the normalized table


from orders.

In practice, concatenated
keys can be implemented
with single primary key.

To tell the DB that we have


foreign keys here, we use the
constraint references
table_name(attr_name)
Now, check if you have this
Generate by right-clicking on your database, then selecting “ERD for
Database”

23 PREPARED BY CASONDAY
PG data types
Boolean (bool) – true or false
Character → char, varchar, text
Numeric → integer, float
Date, time, timestamp, interval
Array
JSON
Hstore

More details:
https://www.postgresql.org/docs/current/datatype.html#DATATYPE-
TABLE

24 PREPARED BY CASONDAY
Other DDL Commands
INSERT – adds a data object to the table specified
UPDATE – updates values in a table given the specified filters
DELETE
ALTER

25 PREPARED BY CASONDAY
Create the table

For the next series of examples, let us build this table.


Inserting Rows
INSERT INTO TableName (column1, column2, …)
VALUES (value1, value2,…),
(value1, value2, …);

Use the command table


<table_name> to show the data in
the tables

You can run two insert commands as


long as you end each one with a
semicolon (;)
Inserting Rows
INSERT INTO TableName (column1, column2, …)
VALUES (value1, value2,…),
(value1, value2, …);
Adding Attributes
ALTER TABLE <TableName> ADD COLUMN <ColumName>
<DataType>;

The new default values will only apply


to new data
Adding Attributes

30 PREPARED BY CASONDAY
Updating Rows
UPDATE TableName
SET columnName1 = dataValue1
[, columnName2 = dataValue2...]
[WHERE searchCondition]

TableName can be name of a base table or an updatable view.


SET clause specifies names of one or more columns that are to be updated.
Updating Rows
WHERE clause is optional:
◦ if omitted, named columns are updated for all rows in table;
◦ if specified, only those rows that satisfy searchCondition are updated.

New dataValue(s) must be compatible with data type for corresponding


column.
Updating Rows
Let us edit the null values for last_update
Updating Rows
Deleting Rows
DELETE FROM TableName
[WHERE searchCondition]

TableName can be name of a base table or an updatable view.


searchCondition is optional; if omitted, all rows are deleted from table. This
does not delete table. If search_condition is specified, only those rows that
satisfy condition are deleted.
Deleting Rows
Normalized Dataset Example
Textbooks

Book-N Book-M Primary-Author-N Book-Topic


25621 Design of Experiments 336 IS
02871 Analysis of Lean Production Systems 225 PS
16121 Fifty Shades of SQL 125 IMS
22654 Linear Regression 336 IS

Authors

Primary-Author- First-M Last-M


N
125 Teresa Wu
336 Douglas Montgomery
225 Ronald Askin
Foreign Key Relationships

Book-N Book-M Primary-Author-N Book-Topic


25621 Design of 336 IS
Experiments
02871 Analysis of Lean 225 PS
Production
Systems
16121 Fifty Shades of SQL 125 IMS
22654 Linear Regression 336 IS

Primary-Author- First-M Last-M


N
125 Teresa Wu
336 Douglas Montgomery
225 Ronald Askin
Foreign Key Relationships
CREATE SCHEMA LibraryDB;

CREATE TABLE Authors(

Primary-Author-N Integer(3) NOT NULL,

First-M VarChar (50),

Last-M VarChar (50) NOT NULL, This is another way


to define a primary
PRIMARY KEY (Primary-Author-N)) ;
key. The first one is
CREATE TABLE Textbooks( simpler, of course.
Book-N Integer(10) NOT NULL,

Book-M VarChar (50) NOT NULL,

Primary-Author-N Int(3) NOT NULL,

Book-Topic Subject, This is another way


PRIMARY KEY (Book-N), to define a foreign
key. The first one is
FOREIGN KEY (Primary-Author-N) REFERENCES simpler, of course.
Authors(Primary-Author-N)) ;
Foreign Key Relationships
CREATE SCHEMA LibraryDB;

CREATE TABLE Authors(

Primary-Author-N Integer(3) NOT NULL,

First-M VarChar (50),

Last-M VarChar (50) NOT NULL, This is another way


to define a primary
PRIMARY KEY (Primary-Author-N)) ;
key. The first one is
CREATE TABLE Textbooks( simpler, of course.
Book-N Integer(10) NOT NULL,

Book-M VarChar (50) NOT NULL,

Primary-Author-N Int(3) NOT NULL,

Book-Topic Subject, This is another way


PRIMARY KEY (Book-N), to define a foreign
key. The first one is
FOREIGN KEY (Primary-Author-N) REFERENCES simpler, of course.
Authors(Primary-Author-N)) ;
Exercise
Create a new database named SQL_Example91
Build the following schema. Ensure that primary key and foreign key
constraints are imposed. Feel free to setup default values.

Note: you may substitute concatenated keys with a single attribute.

41 PREPARED BY CASONDAY
Thank you for coming to
class! Have a nice day!

PREPARED BY CASONDAY 42

You might also like