You are on page 1of 49

Topic 07

Introduction to SQL – Part 1

Nebojša Bačanin Džakula, PhD


nbacanin@singidunum.ac.rs
Faculty of Technical Sciences, Singidunum University
Database Systems
2019/20
2

Notation used in presentations

▪ Each presentation represents one topic, or part of the topic.

▪ Materials within each topic are divided into Sections (for example 3),
which are further divided into Subsections (for example 3.4).

▪ Important definitions and terms are given in this type of


textbox.

▪ SQL code is given in this type of textbox.


Note

▪ Notes and remarks are given in callouts like this


Contents
1. Introduction to SQL and Oracle Application Express (APEX)
2. SQL learning environment setup
3. SQL DML Statements

3
1. Intoduction to SQL and Oracle Application
Express (APEX)

4
1.1 Oracle Application Express (APEX)
• Oracle Application Express is a web-based development and deployment
tool that is available with the Oracle database.
• It enables you to create database-centric web applications that are
reliable, scalable, and secure.
• It has several built-in features and wizards that quicken your development
process.
• The tool has a user-friendly graphical interface. Using Oracle Application
Express requires minimal programming knowledge.

5
• The APEX tool has three components:
1. SQL Workshop
2. Application Builder
3. Object Browser
• For learning SQL, we should use the SQL Workshop component.
• To design an application, we should use Application Builder.

6
• To log to an Oracle Application Express workspace we should do the
following:
• Enter the correct URL (Uniform Resource Locator) address in the browser.
The correct address is: https://apex.oracle.com/en/
• Enter the workspace name
• Enter the username and password
• Click Sign in.

7
1.1.1 SQL Workshop
• SQL Workshop is a tool in Application Express that you use to interact with
the database objects.
• You can create, view, and edit database objects.
• You can also perform tasks, such as loading and unloading data to and
from database tables, generating data definition language (DDL)
statements, and viewing reports.
• SQL Workshop consists of five components:
1. Object Browser: Enables you to browse, create, and edit objects in a
database
2. SQL Commands: Enables you to create, edit, view, run, and delete
database objects

8
3. SQL Scripts: Is a set of SQL commands saved as a file in SQL Scripts. A SQL
script can contain one or more SQL statements or PL/SQL blocks. You can
use SQL Scripts to create, edit, view, run, and delete database objects.
4. Utilities: Enables you to build SQL queries, load and unload data from an
Oracle database, generate DDL, view object reports, manage User
Interface defaults, restore dropped database objects, compare schemas,
monitor the database, and view database details
5. RESTful Services: Enables the declarative specification of RESTful Web
Services used to access the database. These services work in conjunction
with the Oracle Application Express Listener to enable the consumption
of these services.

9
1.1.2. Running SQL commands
• To execute SQL code with SQL Commands, perform the following steps: •
1. Navigate to the SQL Commands page by selecting SQL Commands from
the drop-down menu on the SQL Workshop tab.
2. Enter the SQL or PL/SQL statement in the command editor.
3. Click the Run button.
4. View the output on the Results tab of the display pane.
5. (Optional) Click the Download link to export the results of the query to a
spreadsheet in Microsoft Excel.

10
1.1.3 Import and run a SQL Script
• The steps for importing and running an SQL script are shown in the picture
presented on this slide.

11
1.2 Introduction to SQL
• SQL (Structured Query Language) is the set-based, declarative language
used to access data in an Oracle or other databases, like MySQL, MariaDB,
Microsoft SQL Server, etc.
• SQL provides an interface to a relational database and provides
statements that help work with the database.

12
• In a relational database, you do not specify the access route to the tables,
and you do not need to know how the data is arranged physically.
• To access the database, you execute a SQL statement, which is the
American National Standards Institute (ANSI) standard language for
operating relational databases.
• SQL is also compliant with ISO Standard (SQL 1999).
• SQL is a set of statements with which all programs and users access data
in an Oracle database.
• Application programs and Oracle tools often allow users access to the
database without using SQL directly, but these applications, in turn, must
use SQL when executing the user's request.

13
• SQL is:
➢ The ANSI standard language for operating relational databases
➢ Efficient, easy to learn, and use
➢ Functionally complete (With SQL, you can define, retrieve, and manipulate data in the
tables.)
• Basic functions of SQL are:
➢ Creating, replacing, altering and dropping database object.
➢ Inserting, updating and deleting rows in a table.
➢ Querying data stored in the database
➢ Controlling access to the database and database objects.
➢ Guaranteeing database consistency and integrity.

14
• SQL provide benefits to all types of users:
1. Application programmers
2. Database administrators
3. Managers
4. End users
• SQL processes sets of data as groups rather than as individual units.
• It allows users to:
1. Access and describe the data stored in the database
2. Define the data stored in the database and manipulate that data

15
1.2.1 SQL Processing
• SQL Processing consists of four stages.
• These stages are shown on the following Figure.

16
• The first stage of SQL processing is parsing, which involves separating the
pieces of a SQL statement into a data structure that can be processed by
other routines. The database parses a statement when it is instructed by
the application, which means that only the application, not the database
itself, can reduce the number of parses. During the parse, the database
performs a syntax check, semantic check, and shared pool check.
• SQL Optimization: It is the process of selecting the most efficient means
of executing a SQL statement. The database optimizes queries based on
statistics collected about the actual data being accessed. The optimizer
uses the number of rows, the size of the data set, and other factors to
generate possible execution plans, assigning a numeric cost to each plan.
The database uses the plan with the lowest cost.

17
• SQL Row Source Generation: The row source generator is software that
receives the optimal execution plan from the optimizer and produces an
iterative plan, called the query plan, that is usable by the rest of the
database. The iterative plan is a binary program that, when executed,
produces the result set. The query plan takes the form of a combination of
steps. Each step returns a row set. The rows in this set are either used by
the next step or, in the last step, are returned to the application issuing
the SQL statement.
• SQL Execution: The SQL engine executes each row source in the tree
produced by the row source generator.

18
1.2.2 Types of SQL statements
• There are four basic types of SQL statements:
1. SQL DDL (Data Definition Language) statements that are used for creating
new object in the database. Objects include: tables, indexes, views,
sequences, etc.
2. SQL DML (Data Manipulation Language) statements that are used to
retrieve, update and delete the data from the database.
3. SQL DCL (Data Control Language) statements that are used to control
access and privileges to the objects.
4. SQL TCL (Transaction Control Language) that are used to control and
execute SQL Transactions. Transaction is a sequence of commands that
must be executed in a row (Example: Transferring money from one
account to another account).

19
• SQL DDL Commands: CREATE, ALTER, DROP, TRUNCATE.
• SQL DML Commands: SELECT, UPDATE, DELETE, INSERT, MERGE.
• SQL DCL Commands: GRANT, REVOKE.
• SQL TCL Commands: COMMIT, ROLLBACK, SAVEPOINT.

20
2. SQL learning environment setup

21
• For the purpose of learning SQL we will use Oracle APEX and Oracle SQL
Developer with Oracle Database 12c Express, which is installed locally (on
local computer).
• First, we will upload and execute the script PLSQL_Schema.sql in Oracle
APEX.
• This script is available with the course materials.
• The script contains SQL statements for creating sample databases which
consists of many tables joined together using 1:1, 1:Many and Many:Many
relations.
• The script contains many databases, but for the learning purposes, we will
use the database EMPLOYEES/DEPARTMENTS.
• ERD for this database and respected relational model are shown on the
next slides.

22
• Also, we want to implement EMPLOYEES/DEPARTMENTS database on
locally installed Oracle Database Server 12c.
• First, we connect to our database instance using Oracle SQL Developer.
• Now let’s suppose that PLSSQL_Schema.sql script is located on our local
computer in the following location: D:\PLSQL_Schema.sql.
• In the Query Builder of SQL Developer, we issue the following command:
@D:\PLSQL_Schema.sql;

• In this way, by executing this script, EMPLOYEES/DEPARTMENTS database


will be implemented on our server.
• Screenshot is shown in the next slide.

23
24
2.1 EMPLOYEES/DEPARTMENTS ERD

25
2.2 EMPLOYEES/DEPARTMENTS Relational Model

26
• We will use SQL WorkShop – SQL Commands component of the APEX to
create and to execute SQL commands.
• We will also use SQL Developer Query Builder to execute SQL
commands.

27
3. SQL DML Statements

28
• Basic SQL DML Statements are: SELECT, UPDATE, DELETE, INSERT and
MERGE.
• In the following slides, we will take a deeper look into the syntax and
examples of using these statements.
• All SQL statements must end with semicolon (;)

29
3.1 SQL Describe
• Although, SQL describe does not belong to the group of SQL DML
Statements, it is very useful command.
• SQL Describe is used to see the definition of the table (column names and
types, constraitns, etc.).

DESCRIBE table_name;

DESCRIBE employees;

• We just need to enter the command in the SQL Command APEX’s


windows, and to click run (take a look into the following slide).

30
31
3.2 SQL SELECT
• The SELECT statement is used to select data from a database.
• The data returned is stored in a result table, called the result-set.

SELECT column1, column2, ...


FROM table_name;

SELECT employee_id,first_name,last_name,email
FROM employees;

32
• The process of selecting columns is called SQL Projection.
• Using SQL Projection we select columns that should be displayed as an
output of the SQL query.
• When using asterisk (*) with SQL Select, that means that we want to
select all columns from the table.

SELECT * FROM table_name;

SELECT * FROM employees;

33
3.3 SQL SELECT DISTINCT
• The SELECT DISTINCT statement is used to return only distinct (different)
values.
• Inside a table, a column often contains many duplicate values; and
sometimes you only want to list the different (distinct) values.
• The SELECT DISTINCT statement is used to return only distinct (different)
values.

SELECT DISTINCT column1, column2, ...


FROM table_name;

SELECT DISTINCT
employee_id,first_name,last_name,email
FROM employees;

34
SELECT COUNT(DISTINCT(country_ID))
FROM countries;

SELECT COUNT(*) AS DistinctCountries


FROM (SELECT DISTINCT country_id FROM
countries)

• AS is used to give an alias for the column. In this example, alias for
COUNT(*) function is DistictCountries.

35
3.4 SQL WHERE CLAUSE
• The WHERE clause is used to filter records.
• The WHERE clause is used to extract only those records that fulfill a
specified condition.
• The WHERE clause is used to perform the process of selection.
• The process of selection is used to filter records (to show only certain
records in the result of the SQL query).

SELECT column1, column2, ...


FROM table_name
WHERE condition;

SELECT * FROM employees WHERE


last_name='King';

36
• When using the WHERE clause, string conditions must be placed within
the single quotes (‘).
• When the condition in WHERE clause is numeric, we do not use quotes.

SELECT * FROM employees WHERE


last_name='King' AND
job_id='AD_PRES';

SELECT * FROM employees WHERE


employee_id=100;

37
• Operators (<,>,=,etc.) can be used in the WHERE clause.
• The allowed operators in the WHERE clause are shown in the following
table.

38
3.5 SQL AND, OR and NOT Operators
• The WHERE clause can be combined with AND, OR, and NOT operators.
• The AND and OR operators are used to filter records based on more than
one condition:
• The AND operator displays a record if all the conditions separated by AND
is TRUE.
• The OR operator displays a record if any of the conditions separated by
OR is TRUE.
• The NOT operator displays a record if the condition(s) is NOT TRUE.

39
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND
condition2 AND condition3
...;

SELECT column1, column2, ...


FROM table_name
WHERE condition1 OR
condition2 OR condition3 ...;

SELECT column1, column2, ...


FROM table_name
WHERE NOT condition;

40
SELECT first_name,last_name FROM
employees WHERE employee_id>100 AND
last_name!='Abel';

SELECT * FROM employees WHERE


department_id=90 OR salary>20000;

SELECT * FROM employees WHERE


employee_id>120 AND
hire_date>'06/17/2002';

41
3.6 SQL ORDER BY
• The ORDER BY keyword is used to sort the result-set in ascending or
descending order.
• The ORDER BY keyword sorts the records in ascending order by default.
• To sort the records in descending order, use the DESC keyword.

SELECT column1, column2, ...


FROM table_name
ORDER BY column1, column2,
... ASC|DESC;

• We can sort rows by one or more columns.

42
SELECT * FROM employees ORDER BY last_name;

SELECT last_name || ' ' || first_name AS


"Full name", salary FROM employees ORDER BY
salary DESC;

• In this example, we used ||.


• The || is concatenate operator, that is used to join two or
more strings together.

43
3.7 SQL NULL VALUES
• A field with a NULL value is a field with no value.
• If a field in a table is optional, it is possible to insert a new record or
update a record without adding a value to this field. Then, the field will be
saved with a NULL value.
• It is very important to understand that a NULL value is different from a
zero value or a field that contains spaces. A field with a NULL value is one
that has been left blank during record creation!
• It is not possible to test for NULL values with comparison operators, such
as =, <, or <>.
• We will have to use the IS NULL and IS NOT NULL operators instead.

44
SELECT column_names
FROM table_name
WHERE column_name IS NULL;

SELECT column_names
FROM table_name
WHERE column_name IS NOT
NULL;

45
SELECT * FROM employees WHERE salary IS NULL;

SELECT last_name,first_name,salary FROM


employees WHERE last_name LIKE 'A%' AND
salary IS NOT NULL;

• In this example we used LIKE operator.


• This operator is used to select values by using patterns.
• The symbol % denotes zero, one or many characters.
• The symbol _ denotes exactly one character.

46
References
1. Oracle Academy courseware (Database Foundations and Database
Design and Programming with SQL), 2015.
2. Burleson, K. D., Physical Database Design Using Oracle (Foundations of
Database Design), 1st Edition, Auerebach Publications, 2006, p. 247.

47
IMPORTANT NOTICE!
Ova prezentacija je nekomercijalna.
Slajdovi mogu da sadrže materijale preuzete sa Interneta, stručne i naučne
građe, koji su zaštićeni Zakonom o autorskim i srodnim pravima. Ova
prezentacija se može koristiti samo privremeno tokom usmenog izlaganja
nastavnika u cilju informisanja i upućivanja studenata na dalji stručni,
istraživački i naučni rad i u druge svrhe se ne sme koristiti –
Član 44 - Dozvoljeno je bez dozvole autora i bez plaćanja autorske naknade za nekomercijalne svrhe nastave:
(1) javno izvođenje ili predstavljanje objavljenih dela u obliku neposrednog poučavanja na nastavi;
- ZAKON O AUTORSKOM I SRODNIM PRAVIMA ("Sl. glasnik RS", br. 104/2009 i 99/2011)
.................................................................................................................................................................................
Nebojša Bačanin Džakula
nbacanin@singidunum.ac.rs

48
Topic 07
Introduction to SQL – Part 1

Thank you for attention!


Nebojša Bačanin Džakula, PhD
nbacanin@singidunum.ac.rs
Faculty of Technical Sciences, Singidunum University
Database Systems
2019/20

You might also like