structured query language (sql) · 2020. 11. 18. · sql acronym for structured query language....

Post on 25-Feb-2021

12 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Structured Query Language (SQL)

TW · Web TechnologiesMIEIC, 2020/21 Edition

Sérgio NunesDEI, FEUP, U.Porto

Partially based on materials from André Restivo, "SQL:DDL", "SQL:DML", "SQL:DQL", Web Technologies course (2018).

Work in progress.

Plan for today

➔ Check group work:

➔ Status of the HTML and CSS development;

➔ Status of the database implementation: creation, population;

➔ Continue SQL introduction: queries

➔ Introduction to PHP

➔ Overview;

➔ Using templates to organize HTML code;

➔ Group work

2

SQL

➔ Acronym for Structured Query Language.

➔ Special purpose language designed to query relational databases.

➔ Established as a standard in 1986.

➔ Provides a uniform interface for relational databases.

➔ Pronounced sequel.

3

Overview

➔ SQL provides a way to:

➔ Define the data structure of a relational database (i.e. create);

➔ Query data stored in a relational database (i.e. select);

➔ Insert or update data stored in a relational database (i.e. insert, update).

➔ These materials adhere as much as possible to the SQL standard, although some details might be specific to SQLite. All examples are for SQLite.

4

SQL Syntax

➔ All SQL statements end with a semicolon (;)

➔ SQL command are usually written in uppercase and specific table names and attributes are written in lowercase.

5

SQL Data Definition Language

6

Creating Tables

➔ The basic structure of a table creation statement in SQL:

➔ Specific example in SQLite for pessoa(id, name, mobile)

7

CREATE TABLE <table_name> ( <column_name> <data_type>, <column_name> <data_type>, ... <column_name> <data_type> );

CREATE TABLE person ( id INTEGER PRIMARY KEY, name TEXT, mobile TEXT );

Deleting Tables

➔ To delete a table, the SQL statement is:

➔ If there are dependencies from other tables (e.g. foreign keys), we need to delete all in cascade. The SQL statement for that is:

8

DROP TABLE <table_name>;

DROP TABLE <table_name> CASCADE;

SQLite Data Types

➔ Core data types in SQLite:

➔ INTEGER: signed integer value;

➔ REAL: floating point values;

➔ TEXT: textual data;

➔ BLOB: binary large object (i.e. for files);

➔ Note the absence of a specific type for dates (common in other databases). In SQLite, dates are manipulated using specific functions — date(), time(), etc.

➔ Also absent is a boolean data type (i.e. true / false). In SQLite booleans are mapped to integers (0 = false and 1 = true).

9

SQLite Attributes Example

➔ student(id, code, name, email, birthdate, course_average, active)

10

CREATE TABLE student ( id INTEGER, code TEXT, name TEXT, email TEXT, birthdate DATE, course_average REAL, active BOOLEAN );

Constraints

11

Not Null Constraint

➔ We can define that certain attributes do not allow NULL values.

12

CREATE TABLE <table_name> ( <column_name> <data_type> NOT NULL, <column_name> <data_type>, ... <column_name> <data_type> );

Unique Values Constraint

➔ We can define that certain attributes do not allow repeated values.

➔ Multiple NULL values can be repeated.

➔ It is possible to define unique constraints for multiple columns.

13

CREATE TABLE <table_name> ( <column_name> <data_type> UNIQUE, <column_name> <data_type>, ... <column_name> <data_type>,

UNIQUE (<column_name>, <column_name>, ...) );

Primary Key Constraint

➔ We can define one, and only one, primary key for a table.

➔ Primary keys are implicitly unique (no repeated values) and not null.

➔ Common use case INTEGER PRIMARY KEY.

14

CREATE TABLE <table_name> ( <column_name> <data_type> PRIMARY KEY, <column_name> <data_type>, ... <column_name> <data_type> );

Multiple Attribute Primary Key Constraint

➔ We can define primary keys composed of multiple attributes.

➔ Common in association classes (e.g. in N-N associations).

15

CREATE TABLE <table_name> ( <column_name> <data_type>, <column_name> <data_type>, ... <column_name> <data_type>,

PRIMARY KEY (<column_name>, <column_name>, ...) );

Foreign Key Constraint

➔ Foreign keys must reference a primary key.

➔ table_A(column_A, column_B, column_C) ➔ table_B(column_X, column_Y, #column_Z → table_A)

16

CREATE TABLE <table_A> ( <column_A> <data_type> PRIMARY KEY, <column_B> <data_type> );

CREATE TABLE <table_B> ( <column_X> <data_type> PRIMARY KEY, <column_Y> <data_type>, <column_Z> <data_type>, FOREIGN KEY (<column_Z>) REFERENCES <table_A> (<column_A>) );

SQLite Example

17

CREATE TABLE student ( id INTEGER PRIMARY KEY, code TEXT NOT NULL, name TEXT NOT NULL, email TEXT, birthdate DATE, course_average REAL, active BOOLEAN, nationality INTEGER,

FOREIGN KEY (nationality) REFERENCES country(id) );

CREATE TABLE country ( id INTEGER PRIMARY KEY, name TEXT NOT NULL );

SQL Data Manipulation Language

18

Insert

19

Inserting Data

➔ To insert values the SQL INSERT command is used.

➔ Specific example for SQLite.

20

INSERT INTO <table_name> (<column_A>, <column_B>, ...) VALUES (<val_A>, <val_B>, ...);

INSERT INTO person (id, name, email) VALUES (1, 'Peter Pan', 'peter@neverland.com');

Inserting Data

➔ We can omit the column names if we insert the values using the same order used to create the table.

21

INSERT INTO person VALUES (1, 'Peter Pan', 'peter@neverland.org');

Delete

22

Deleting Data

➔ To delete data from a table, the SQL DELETE command is used.

➔ The delete command can receive a condition specifying which rows to delete.

➔ If no condition is given, all rows are deleted from the table.

23

DELETE FROM <table_name> WHERE <condition>;

Deleting Data Examples

➔ Delete person with id equal to 1.

➔ Delete all persons.

➔ Delete all persons with salary greater or equal to 10000.

24

DELETE FROM person;

DELETE FROM person WHERE salary >= 10000;

DELETE FROM person WHERE id = 1;

Update

25

Updating Data

➔ To modify data from a table, the SQL UPDATE command is used.

➔ The update command can receive a condition specifying which rows to update.

➔ If no condition is given, all rows form the table are updated.

26

UPDATE <table_name> SET <col1> = <val1>, <col2> = <val2>, ... WHERE <condition>;

Updating Data Examples

➔ Modify the email of the person with id equal to 1.

➔ Increase all salaries in 10%.

➔ Increase all salaries in 10%, but only for salaries lower than 5000.

27

UPDATE person SET salary = salary * 1.1;

UPDATE person SET salary = salary * 1.1 WHERE salary < 5000;

UPDATE person SET email = 'pan@neverland.org' WHERE id = 1;

SQL Data Querying Language

28

Selecting Data

29

Selecting Data

➔ SELECT and FROM are the most basic SQL query operators.

➔ They allow to specify which table (in FROM) and which columns (in SELECT) are to be retrieved from the database.

➔ The result of a SQL query is also a table.

30

SELECT name, email FROM person;

SELECT * FROM country;

Select name and email columns from all records from table person.

Select all columns (asterisk) from all records from table person.

Choosing Columns

➔ Using an asterisk (*) selects all columns.

➔ Identifying columns (separated by commas), selects which columns to include.

31

SELECT id, name, email FROM person;

id name email1 John Doe john@...3 Peter Pan peter@...4 Joan Smith joan@...5 Jane Wiston

Renaming Columns

➔ Any column can be renamed using the AS operator.

32

SELECT id AS code, name, email FROM person;

code name email1 John Doe john@...3 Peter Pan peter@...4 Joan Smith joan@...5 Jane Wiston

Filtering Rows

➔ The WHERE command is used to filter which rows are shown, according to a condition.

➔ The condition can use any comparison operator (<, >, <=, <>, ...) and can be composed using AND, OR and NOT.

33

SELECT * FROM employee WHERE department = 2 AND salary <= 1000;

Select all columns where department is equal to 2 and salary is lower or equal to 1000 from table employee.

Filtering Rows - NULL Operator

➔ To test if a value is NULL, we have to use the special IS NULL operator.

➔ The condition can use any comparison operator (<, >, <=, <>, ...) and can be composed using AND, OR and NOT.

34

SELECT * FROM employee WHERE department IS NULL;

Select all columns where department is not defined from table employee.

Remove Duplicates

➔ Duplicate values can be removed from the results using the DISTINCT operator.

35

SELECT DISTINCT salary FROM employee;Select all the existing different salaries from table employee.

salary1000110010001300

SELECT salary FROM employee;

salary100011001300

Select all the existing salaries from table employee.

Ordering Results

➔ The default order by which rows are sorted in query results is unpredictable.

➔ Results can be sorted using the ORDER BY clause. Default is ascending.

36

SELECT * FROM employee ORDER BY name;Select all the existing information from table employee and order by the name atribute .

SELECT * FROM employee;Select all the existing information from table employee.

code name email1 John Doe john@...3 Peter Pan peter@...4 Joan Smith joan@...5 Jane Wiston

code name email5 Jane Wiston4 Joan Smith joan@...1 John Doe john@...3 Peter Pan peter@...

Ordering Results

➔ Sort order can be defined with ASC (ascending) or DESC (descending).

➔ Multiple columns can be defined to sort-by.

37

SELECT * FROM employee ORDER BY name DESC, email;Select all the existing information from table employee, and order results first by name in descending order, then, in case of ties, order by email on ascending order (default).

Joining Tables

38

Combining Different Tables

➔ You can combine different tables in a single SELECT statement.

➔ The result contains rows with all possible combinations from the selected tables.

➔ This is called the cartesian product, also known as a CROSS JOIN in SQL.

39

Combining Different Tables

40

id name department1 John 12 Mary 23 Alice 24 Peter 2

id name1 Marketing2 Engineering

SELECT * FROM employee; SELECT * FROM department;

id name department id name1 John 1 1 Marketing2 Mary 2 1 Marketing3 Alice 2 1 Marketing4 Peter 2 1 Marketing1 John 1 2 Engineering2 Mary 2 2 Engineering3 Alice 2 2 Engineering4 Peter 2 2 Engineering

SELECT * FROM employee, department;

➔ The WHERE command can be used to filter columns.

Filtering Valid Columns

41

id name department id name1 John 1 1 Marketing2 Mary 2 1 Marketing3 Alice 2 1 Marketing4 Peter 2 1 Marketing1 John 1 2 Engineering2 Mary 2 2 Engineering3 Alice 2 2 Engineering4 Peter 2 2 Engineering

SELECT * FROM employee, department WHERE employee.department = department.id;

➔ Columns can be renamed using the AS operator

Handling Duplicate Column Names

42

id name department1 John Marketing

2 Mary Engineering

3 Alice Engineering

4 Peter Engineering

SELECT employee.id, employee.name, department.name AS department FROM employee, department WHERE employee.department = department.id;

Next week tasks

➔ Work on previous tasks:

➔ Share implemented web pages;

➔ Share SQL code: create and population scripts;

➔ Structure page elements using PHP:

➔ Publish and share results on gnomo;

43

top related