You are on page 1of 43

Database Systems

Week 3: Introduction to SQL


Creating tables
• Execute the query.
• You will get: Command(s) completed successfully.
• To view the Employee table in the Company database, expand the Company
node (under the Object Explorer) and the Tables node, and you should be
able to see the Employee table
• To look at the table definition of the table you just created, right-click on the
table, Employee, and select Modify.

• Create a table called Names (type the following query):


• CREATE TABLE Names (fullname VARCHAR(20))
Inserting Values into a Table
• Two most commonly used ways:
• using INSERT INTO .. VALUES and
• using INSERT INTO .. SELECT.
Using INSERT INTO .. VALUES
• INSERT INTO .. VALUES option needs the column list and all the
columns in the correct order.
• The general syntax for the INSERT INTO .. VALUES option is:

INSERT INTO TableName VALUES ('character_attribute_value',


numeric_attribute_value, ...)

INSERT INTO Names VALUES ('Joe Smith')


Using INSERT INTO .. VALUES
• To insert into the Employee table that you created earlier, the INSERT
INTO .. VALUES statement to insert a row would have to match
column for column and would look like this:

INSERT INTO Employee VALUES ('Joe Smith', '123 4th St.', 101, 2500)
Using INSERT INTO .. VALUES
• You may INSERT a row with less than all the columns by naming the
columns you want to insert into, like this:
• INSERT INTO Employee (names, address) VALUES ('Joe Smith', '123
4th St.')
• The row will contain nulls or default values for the values left out,
which you will see if you type:
SELECT * FROM Employee
• Values MUST be inserted in the same order as the definition of the
table:
Using INSERT INTO .. SELECT
• INSERT INTO .. VALUES option, you insert only one row at a time into a
table. With the INSERT INTO .. SELECT option, you may (and usually
do) insert many rows into a table at one time.
• The general syntax for the INSERT INTO .. SELECT option is:
INSERT INTO target_table(column1, column2, column3, ...)
"SELECT clause"
• To copy all the names from the Employee table into the Names table,
type the following:
INSERT INTO Names(fullname)
SELECT names FROM Employee
Using INSERT INTO .. SELECT
• You could restrict the INSERT .. SELECT like this:
INSERT INTO Names(fullname)
SELECT names FROM Employee
WHERE salary > 2600
Using UPDATE
• You often UPDATE more than one row. To examine how the UPDATE
command works, we will use the tables we created.
• The general format for the UPDATE command is:
UPDATE TableName SET fieldname...
• For example, if you want to set all salaries in the table Emp2 to zero,
you may do so with one UPDATE command:
UPDATE Emp2 SET sal = 0
Using UPDATE
• Useful to include a WHERE clause in the UPDATE command so that
values are set selectively.
• UPDATE Employee SET salary = 0
• WHERE employee_number=101
Using DELETE FROM
• To delete all the rows in the Employee table as well as in the Names
table, type:
DELETE FROM Employee
• Then:
DELETE FROM Names
ALTER TABLE Command
• To add, change, and update rows in a table we use INSERT and
UPDATE commands.
• you can add, change (modify), and delete columns in a table's
definition by using SQL's ALTER TABLE command. ALTER TABLE
commands are known as data definition (DDL) commands, because
they change the definition of a table.
Adding a Column to a Table
• The general syntax for adding a column to a table is:
ALTER TABLE Tablename ADD column-name type

• For example, to add a column called bonus (a SMALLMONEY column) to


the Employee table, you type in the following:
ALTER TABLE Employee
ADD bonus SMALLMONEY
• When columns are added to existing tables, they will initially contain
null values. Data may be added to the new column using an UPDATE
command.
Deleting a Column from a Table
• The following is the general syntax for deleting a column from a table:
ALTER TABLE Tablename
DROP column column-name
• For example, to delete the column called bonus from the Employee
table, type the following:
ALTER TABLE Employee
DROP column bonus
ALTER TABLE example
CREATE TABLE employees (
employee_id SERIAL PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100),
hire_date DATE,
salary NUMERIC(10,2)
);

ALTER TABLE employees ADD COLUMN department VARCHAR(50);


ALTER TABLE employees ALTER COLUMN email SET NOT NULL;
ALTER TABLE employees DROP COLUMN salary;
The DELETE Command
• Following is the general syntax of the DELETE command used to delete rows from a
table:
DELETE FROM Table WHERE (condition)

(condition) determines which rows of the table will be deleted. As you saw earlier, if
no WHERE condition is used, all the rows of the table will be deleted.

• Multiple rows can be affected by the DELETE command, so be careful when using it.
Here is an example of using the DELETE command on our original Employee table:
DELETE FROM Employee WHERE salary < 1500
Deleting a Table
• The general syntax to delete or remove an entire table and its
contents is:
DROP TABLE Tablename
• For example, to delete the table called Names from your database,
you would type the following:
DROP TABLE Names
CREATE SCHEMA example
CREATE SCHEMA sales;

CREATE TABLE sales.orders (


order_id SERIAL PRIMARY KEY,
customer_name VARCHAR(50),
order_date DATE,
total_amount NUMERIC(10,2)
);

INSERT INTO sales.orders (customer_name, order_date, total_amount)


VALUES ('John Smith', '2022-03-15', 1250.50),
('Jane Doe', '2022-03-17', 980.75);

SELECT * FROM sales.orders;


Week 4: Relational Data Model
A Logical View of Data
• Relational model
• View data logically rather than physically
• Relational database model is easier to understand than hierarchical
and network models
• Logical view of relational database is based on relation
• Relation thought of as a table
Tables and Their Characteristics
• Table: two-dimensional structure composed of rows and columns
• Persistent representation of logical relation
• Table
• Structural and data independence
• Resembles a file conceptually
• Contains group of related entities (entity set)
Characteristics of a Relational Table
Table Example
Student Classification
Keys
• In the relational model, keys are important because they are used to
ensure that each row in a table is uniquely identifiable.
• They are also used to establish relationships among tables and to
ensure the integrity of the data.
• A key consists of one or more attributes that determine other
attributes.
• For example, an invoice number identifies all of the invoice attributes,
such as the invoice date and the customer name.
Keys
• Each row in a table must be uniquely identifiable
• Key: one or more attributes that determine other attributes
• Key’s role is based on determination
• If you know the value of attribute A, you can determine the value of attribute B
• Functional dependence
• Attribute B is functionally dependent on A if all rows in table that agree in value for A
also agree in value for B
Types of Keys
• Super key
• An attribute or combination of attributes that uniquely identifies each row in a table
• Candidate key
• A minimal (irreducible) super key; a super key that does not contain a subset of
attributes that is itself a super key
• Primary key (PK)
• A candidate key selected to uniquely identify all other attribute values in any given
row; cannot contain null entries.
• Foreign key (FK)
• An attribute or combination of attributes in one table whose values must either
match the primary key in another table or be null.
Types of Keys
• Referential integrity
• FK contains a value that refers to an existing valid tuple (row) in another
relation
• Secondary key
• Key used strictly for data retrieval purposes
Types of Keys
• Entity integrity
• Each row (entity instance) in the table has its own unique identity
• Nulls
• No data entry
• Not permitted in primary key
• Should be avoided in other attributes
Types of Keys
• Can represent:
• An unknown attribute value
• A known, but missing, attribute value
• A “not applicable” condition
• Can create problems when functions such as COUNT, AVERAGE, and
SUM are used
• Can create logical problems when relational tables are linked
Types of Keys
• Controlled redundancy
• Makes the relational database work
• Tables within the database share common attributes
• Enables tables to be linked together
• Multiple occurrences of values not redundant when required to make the
relationship work
• Redundancy exists only when there is unnecessary duplication of attribute
values
Relational Database Keys
Relational Database Example
Relationships within the Relational Database
• 1:M relationship
• Relational modeling ideal
• Should be the norm in any relational database design
• 1:1 relationship
• Should be rare in any relational database design
• M:N relationships
• Cannot be implemented as such in the relational model
• M:N relationships can be changed into 1:M relationships
The 1:M Relationship
• Relational database norm
• Found in any database environment
1:M Relationship Example
The 1:1 Relationship
• One entity related to only one other entity, and vice versa
• Sometimes means that entity components were not defined properly
• Could indicate that two entities actually belong in the same table
• Certain conditions absolutely require their use
1:1 Relationship Example
The M:N Relationship
• Implemented by breaking it up to produce a set of 1:M relationships
• Avoid problems inherent to M:N relationship by creating a composite
entity
• Includes as foreign keys the primary keys of tables to be linked
M:N Relationship Example
M:N Relationship to 1:M Example
M:N Relationship to 1:M Example

You might also like