You are on page 1of 22

Database Systems

Structured Query Language


Ing. Andrs Scoccimarro
Profesor Adjunto

Introduction
Structured Query Language, is a database computer language designed for managing data in relational database management systems (RDBMS), and originally based upon relational algebra and calculus. Its scope includes data insert, query, update and delete, schema creation and modification, and data access control.

Introduction (Cont.)
SQL was developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in the early 1970s. This version, initially called SEQUEL (Structured English Query Language), was designed to manipulate and retrieve data stored in IBM's original quasi-relational database management system, System R, which a group at IBM San Jose Research Laboratory had developed during the 1970s. The acronym SEQUEL was later changed to SQL because "SEQUEL" was a trademark of the UK-based Hawker Siddeley aircraft company.

What is SQL?
SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL is an ANSI (American National Standards Institute) standard

What Can SQL do?


SQL SQL SQL SQL can can can can execute queries against a database retrieve data from a database insert records in a database update records in a database
1 of 22

Database Systems

SQL SQL SQL SQL SQL SQL

can can can can can can

delete records from a database create new databases create new tables in a database create stored procedures in a database create views in a database set permissions on tables, procedures, and views

SQL is a Standard - BUT...


Although SQL is an ANSI (American National Standards Institute) standard, there are many different versions of the SQL language. However, to be compliant with the ANSI standard, they all support at least the major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner. Note : Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard!

SQL DML, DDL and DCL


SQL can be divided into three parts: The Data Manipulation Language (DML), the Data Definition Language (DDL) and the Data Control Lenguage (DCL). The query and update commands form the DML part of SQL: SELECT - extracts data from a database UPDATE - updates data in a database DELETE - deletes data from a database INSERT INTO - inserts new data into a database

SQL DML, DDL and DCL (cont.)


The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys), specify links between tables, and impose constraints between tables. The most important DDL statements in SQL are: CREATE DATABASE - creates a new database ALTER DATABASE - modifies a database CREATE TABLE - creates a new table ALTER TABLE - modifies a table DROP TABLE - deletes a table CREATE INDEX - creates an index (search key)
2 of 22

Database Systems

DROP INDEX - deletes an index CREATE VIEW - creates a view DROP VIEW - deletes a view

SQL DML, DDL and DCL (cont.)


The DCL authorizes users and groups of users to access and manipulate data. Its two main statements are: GRANT - authorizes one or more users to perform an operation or a set of operations on an object. REVOKE - eliminates a grant, which may be the default grant.

The SQL SELECT Statement


The SELECT statement is used to select data from a database. The result is stored in a result table, called the result-set. SQL SELECT Syntax SELECT [DISTINCT] column_name(s) [AS alias_name] FROM table_name(s) [alias_name] WHERE condition(s) GROUP BY column_name(S) [HAVING condition(S)] ORDER BY column_name(S)

The SQL SELECT DISTINCT Statement


In a table, some of the columns may contain duplicate values. This is not a problem, however, sometimes you will want to list only the different (distinct) values in a table. The DISTINCT keyword can be used to return only distinct (different) values. SQL SELECT DISTINCT Syntax SELECT DISTINCT column_name(s) FROM table_name(s)

3 of 22

Database Systems

The WHERE Clause


The WHERE clause is used to extract only those records that fulfill a specified criterion. SQL WHERE Syntax SELECT column_name(s) FROM table_name(s) WHERE column_name operator value

Operators Allowed in the WHERE Clause


With the WHERE clause, the following operators can be used:
Operator = <> > < >= <= LIKE IN Equal Not equal Greater than Less than Greater than or equal Less than or equal Search for a pattern If you know the exact value you want to return for at least one of the columns Description

BETWEEN Between an inclusive range

Note: In some versions of SQL the <> operator may be written as !=

The AND & OR Operators


The AND operator displays a record if both the first condition and the second condition is true. The OR operator displays a record if either the first condition or the second condition is true. AND & OR Operators Syntax SELECT column_name(s) FROM table_name(s) WHERE column_name operator value

4 of 22

Database Systems

AND/OR column_name operator value

The ORDER BY Keyword


The ORDER BY keyword is used to sort the result-set by a specified column. The ORDER BY keyword sort the records in ascending order by default. If you want to sort the records in a descending order, you can use the DESC keyword. SQL ORDER BY Syntax SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC

The LIKE Operator


The LIKE operator is used to search for a specified pattern in a column. SQL LIKE Syntax SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern

SQL Wildcards
SQL wildcards can substitute for one or more characters when searching for data in a database. SQL wildcards must be used with the SQL LIKE operator. With SQL, the following wildcards can be used:
Wildcard % _ [charlist] Description A substitute for zero or more characters A substitute for exactly one character Any single character in charlist

[^charlist] or Any single character not in charlist [!charlist]

5 of 22

Database Systems

The BETWEEN Operator


The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or dates. SQL BETWEEN Syntax SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2

SQL NULL Values


The idea of Null was introduced into SQL to handle missing information in the relational model. The introduction of Null (or Unknown) along with True and False is the foundation of three-valued logic. Null does not have a value (and is not a member of any data domain) but is rather a placeholder or "mark" for missing information. Therefore comparisons with Null can never result in either True or False but always in the third logical result If a column in a table is optional, we can insert a new record or update an existing record without adding a value to this column. This means that the field will be saved with a Null value.

SQL NULL Values


Null values are treated differently from other values. Null is used as a placeholder for unknown or inapplicable values. As consequence: Null <> Null or Null <> X ? Unknown. Null = Null or Null = X ? Unknown. Since SQL operators return Unknown when comparing anything with Null, SQL provides two Null-specific comparison predicates: IS NULL and IS NOT NULL test whether data is or is not Null.

SQL IS NULL / IS NOT NULL


How do we select only the records with Null values in the column? We will have to use the IS Null operator:

6 of 22

Database Systems

SELECT column_name(s) FROM table_name WHERE column_name IS NULL How do we select only the records with no Null values in the column We will have to use the IS NOT Null operator: SELECT column_name(s) FROM table_name WHERE column_name IS NOT NULL

The IN | NOT IN Operator


The IN operator allows you to specify multiple values in a WHERE clause. SQL IN Syntax SELECT column_name(s) FROM table_name WHERE column_name IN | NOT IN (value1,value2,...)

The SOME | ANY | ALL Operators


The SOME | ANY | ALL operators allow you to specify an arithmetic comparison on multiple values in the WHERE clause. SQL IN Syntax SELECT column_name(s) FROM table_name WHERE column_name operator ANY | SOME | ALL (value1,value2,...)

Cartesian product
To make a cartesion product the only thing that you need to do is add more than one table on the FROM statement. Cartesion product Syntax SELECT column_name(s) FROM table_name1, table_name2

7 of 22

Database Systems

SQL JOIN
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables. Tables in a database are often related to each other with keys. A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table.

SQL JOIN (Cont.)


Different SQL JOINs INNER JOIN: Return rows when there is at least one match in both tables OUTER JOIN: Return rows when there is a match in one of the tables LEFT OUTER JOIN: Return all rows from the left table, even if there are no matches in the right table. RIGHT OUTER JOIN: Return all rows from the right table, even if there are no matches in the left table. FULL OUTER JOIN: Return rows when there is a match in one of the tables.

SQL INNER JOINs


SQL NATURAL JOIN Syntax SELECT column_name(s) FROM table_name1 NATURAL JOIN table_name2

SQL INNER JOINs (Cont.)


SQL JOIN Syntax SELECT column_name(s) FROM table_name1 JOIN table_name2 USING (column_name(s))

8 of 22

Database Systems

SQL INNER JOINs (Cont.)


SQL JOIN Syntax SELECT column_name(s) FROM table_name1 JOIN table_name2 ON table_name1.column_name = table_name2.column_name

SQL OUTER JOINs


SQL LEFT OUTER JOIN Syntax SELECT column_name(s) FROM table_name1 LEFT OUTER JOIN table_name2 ON table_name1.column_name = table_name2.column_name

SQL OUTER JOINs (Cont.)


SQL RIGHT JOIN Syntax SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name = table_name2.column_name

SQL OUTER JOINs (Cont.)


SQL FULL OUTER JOIN Syntax SELECT column_name(s) FROM table_name1 FULL OUTER JOIN table_name2 ON table_name1.column_name = table_name2.column_name

SQL Aggregate Functions


SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions:

9 of 22

Database Systems

AVG() - Returns the average value COUNT() - Returns the number of rows FIRST() - Returns the first value LAST() - Returns the last value MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum

The GROUP BY Statement


The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns. SQL GROUP BY Syntax SELECT column_name(s), aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name

The HAVING Clause


The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions. SQL HAVING Syntax SELECT column_name(s), aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value

The SQL UNION Operator


The UNION operator is used to combine the result-set of two or more SELECT statements. Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order. SQL UNION Syntax

10 of 22

Database Systems

SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2

The EXISTS / NOT EXISTS Operator


The EXISTS / NOT EXISTS operator is considered "to be met" if the subquery returns at least one row. Notice that the EXISTS operator can use the tables of the parent query in the subquery. SQL EXISTS Syntax SELECT column_name(s) FROM table_name WHERE EXISTS / NOT EXISTS (subquery)

The CREATE DATABASE Statement


The CREATE DATABASE statement is used to create a database. SQL CREATE DATABASE Syntax: CREATE DATABASE database_name

The CREATE TABLE Statement


The CREATE TABLE statement is used to create a table in a database. SQL CREATE TABLE Syntax CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... ) Note: The data type specifies what type of data the column can hold.

SQL Data types


11 of 22

Database Systems

Each column in an SQL table declares the type(s) that column may contain. ANSI SQL includes the following datatypes. Character (alphanumeric) strings CHARACTER(n) or CHAR(n) - fixed-width n-character string, padded with spaces as needed CHARACTER VARYING(n) or VARCHAR(n) - variable-width string with a maximum size of n characters NATIONAL CHARACTER(n) or NCHAR(n) - fixed width string supporting an international character set NATIONAL CHARACTER VARYING(n) or NVARCHAR(n) variable-width NCHAR string

SQL Data types (Cont.)


Bit strings BIT(n) - an array of n bits BIT VARYING(n) - an array of up to n bits Numbers INTEGER and SMALLINT FLOAT, REAL and DOUBLE PRECISION NUMERIC(precision, scale) or DECIMAL(precision, scale)

SQL Data types (Cont.)


Date and time DATE - for date values (e.g., 2010-05-30) TIME - for time values (e.g., 14:55:37). The granularity of the time value is usually a tick (100 nanoseconds). TIME WITH TIME ZONE or TIMESTAMP - the same as TIME, but including details about the time zone in question. TIMESTAMP - This is a DATE and a TIME put together in one variable (e.g., 2010-05-30 14:55:37). TIMESTAMP WITH TIME ZONE or TIMESTAMPTZ - the same as TIMESTAMP, but including details about the time zone in question.

SQL Constraints
Constraints are used to limit the type of data that can go into a table. Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE
12 of 22

Database Systems

statement). We will focus on the following constraints: NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK DEFAULT

SQL NOT NULL Constraint


The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field.

SQL NOT NULL Constraint (Cont.)


The following SQL enforces the "column_name1" column to not accept NULL values: CREATE TABLE table_name ( column_name1 data_type NOT NULL, column_name2 data_type, column_name3 data_type, .... )

SQL UNIQUE Constraint


The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it. Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

13 of 22

Database Systems

SQL UNIQUE Constraint (Cont.)


The following SQL creates a UNIQUE constraint on the "column_name1" column when the "table_name" table is created: CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... CONSTRAINT constraint_name UNIQUE (column_name1) )

SQL PRIMARY KEY Constraint


The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys must contain unique values. A primary key column cannot contain NULL values. Each table should have a primary key, and each table can have only ONE primary key.

SQL PRIMARY KEY Constraint (Cont.)


The following SQL creates a PRIMARY KEY on the "column_name1" column when the "table_name" table is created: CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... CONSTRAINT constraint_name PRIMARY KEY (column_name1) )

14 of 22

Database Systems

SQL FOREIGN KEY Constraint


A FOREIGN KEY in one table points to a PRIMARY KEY in another table. The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. The FOREIGN KEY constraint also prevents that invalid data form being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.

SQL FOREIGN KEY Constraint (Cont.)


The following SQL creates a FOREIGN KEY on the "column_name1" column when the "table_name" table is created: CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, .... CONSTRAINT constraint_name FOREIGN KEY (column_name1) REFERENCES reference_table(reference_column_name) )

SQL CHECK Constraint


The CHECK constraint is used to limit the value range that can be placed in a column. If you define a CHECK constraint on a single column it allows only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.

SQL CHECK Constraint (Cont.)


The following SQL creates a CHECK constraint on the "column_name1" column when the "table_name" table is created. The CHECK constraint
15 of 22

Database Systems

specifies that the column "column_name1" must check the condition. CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, .... CONSTRAINT constraint_name CHECK (column_name1 operator value) )

SQL DEFAULT Constraint


The DEFAULT constraint is used to insert a default value into a column. The default value will be added to all new records, if no other value is specified.

SQL DEFAULT Constraint (Cont.)


The following SQL creates a DEFAULT constraint on the "column_name2" column when the "table_name" table is created: CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type DEFAULT default_value, column_name3 data_type, .... )

Indexes
An index can be created in a table to find data more quickly and efficiently. The users cannot see the indexes, they are just used to speed up searches/queries. Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.
16 of 22

Database Systems

Indexes (Cont.)
SQL CREATE INDEX Syntax CREATE INDEX index_name ON table_name (column_name(s))

CREATE UNIQUE INDEX index_name ON table_name (column_name(s))

SQL CREATE VIEW Statement


In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table.

SQL CREATE VIEW Statement (Cont.)


SQL CREATE VIEW Syntax CREATE VIEW view_name AS SELECT column_name(s) FROM table_name(s) WHERE condition Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL statement, every time a user queries a view.

SQL DROP Statement


The DROP Statement is used to delete an object SQL DROP syntax:

17 of 22

Database Systems

DROP object_type object_name


object_type is the name of an database object like DATABASE, TABLE, VIEW, STORED PROCEDURE and SEQUENCE. object_name is the name of the database object defined.

The ALTER TABLE Statement


The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. SQL ALTER TABLE Syntax To add a column in a table, use the following syntax: ALTER TABLE table_name ADD column_name datatype

The ALTER TABLE Statement (Cont.)


SQL ALTER TABLE Syntax To delete a column in a table, use the following syntax: ALTER TABLE table_name DROP COLUMN column_name To change the data type of a column in a table, use the following syntax: ALTER TABLE table_name ALTER COLUMN column_name datatype

SQL GRANT Statement


SQL GRANT is a Statement used to provide access or privileges on the database objects to the users. SQL GRANT syntax: GRANT privilege_name ON object_name

18 of 22

Database Systems

TO {user_name | PUBLIC | role_name} [WITH GRANT OPTION];


privilege_name is the access right or privilege granted to the user. Some of the access rights are ALL, EXECUTE, and SELECT. object_name is the name of an database object like TABLE, VIEW, STORED PROC and SEQUENCE. user_name is the name of the user to whom an access right is being granted. PUBLIC is used to grant access rights to all users. ROLES are a set of privileges grouped together. WITH GRANT OPTION - allows a user to grant access rights to other users.

SQL REVOKE Statement


The REVOKE Statement removes user access rights or privileges to the database objects. SQL REVOKE syntax: REVOKE privilege_name ON object_name FROM {user_name | PUBLIC | role_name}
privilege_name is the access right or privilege revoke to the user. Some of the access rights are ALL, EXECUTE, and SELECT. object_name is the name of an database object like TABLE, VIEW, STORED PROC and SEQUENCE. user_name is the name of the user to whom an access right is being revoked. PUBLIC is used to revoke access rights to all users. ROLES are a revoke of privileges grouped together.

SQL STORE PROCEDURE Statement


Stored procedures are essentially functions that you can create in the database and reuse. Stored procedure by definition is a segment of code which contains declarative or procedural SQL statements. A stored procedure is resided in the catalog of the database server so we can call it from a trigger, another stored procedure or even from client appliations.

SQL STORE PROCEDURE Statement


19 of 22

Database Systems

(Cont.)
SQL STORE PROCEDURE syntax: CREATE PROCEDURE procedure_name param1 data_type = default_value, param2 data_type = default_value, ... AS sql statement

SQL STORE PROCEDURE Statement (Cont.)


SQL STORE PROCEDURE Syntax CALL/EXECUTE procedure_name param1_value , param2_value , ...

Database TRIGGER
A database trigger is procedural code that is automatically executed in response to certain events on a particular table or view in a database. The trigger is mostly used for keeping the integrity of the information on the database.

Database TRIGGER (Cont.)


Triggers are commonly used to: prevent changes (e.g. prevent an invoice from being changed after it's been mailed out) log changes (e.g. keep a copy of the old data) audit changes (e.g. keep a log of the users and roles involved in changes) enhance changes (e.g. ensure that every change to a record is time-stamped by the server's clock)
20 of 22

Database Systems

Database TRIGGER (Cont.)


Triggers are commonly used to: enforce business rules (e.g. require that every invoice have at least one line item) execute business rules (e.g. notify a manager every time an employee's bank account number changes) replicate data (e.g. store a record of every change, to be shipped to another database later) enhance performance (e.g. update the account balance after every detail transaction, for faster queries)

Database TRIGGER (Cont.)


Database TRIGGER syntax: CREATE TRIGGER trigger_name BEFORE | AFTER | INSTEAD OF DELETE | INSERT | UPDATE [OF column_name(s)] ON table_name | view_name [REFERENCING NEW ROW AS new_row_name, OLD ROW AS old_row_name] [FOR EACH ROW] [WHEN condition] BEGIN ... END

Database TRIGGER (Cont.)


Database TRIGGER syntax sample: CREATE TRIGGER trigger_name BEFORE SELECT ON table_name REFERENCING NEW ROW AS new_row_name, OLD ROW AS old_row_name FOR EACH ROW condition;
21 of 22

Database Systems

22 of 22

You might also like