You are on page 1of 25

SQL Language

DDL, DQL, DML, DCL, TCL


Reminder
1. Use this form to confirm your presence at a lecture
2. Review of the previous lecture (Normalization)
3. Laboratory work #2
4. Наступного разу - тест

2
SQL
Structured Query Language (SQL) is a declarative programming language that
is typically used in relational database or data stream management systems.

It was developed by IBM in the early 1970s and is now an official standard
recognized by the American National Standards Institute (ANSI) and the
International Organization for Standardization (ISO).
History and versions
Year Name Comments

1986 SQL-86 First formalized by ANSI.

1992 SQL-92 Major revision (ISO 9075). Do not stop here!

1999 SQL:1999 Added regular expression matching, recursive


queries (e.g. transitive closure), triggers,
support for procedural and control-of-flow
statements, non-scalar types (arrays), and
some object-oriented features (e.g. structured
types).
History and versions
Year Name Comments

2003 SQL:2003 Introduced XML-related features (SQL/XML),


window functions, standardized sequences,
and columns with auto-generated values

2016 SQL:2016 Adds row pattern matching, polymorphic


table functions, JSON.
SQL Sublanguages
Language Command List
DDL CREATE, DROP, ALTER, RENAME,
TRUNCATE
DML SELECT (DQL), INSERT, UPDATE, DELETE

DCL GRANT, REVOKE

TCL START TRANSACTION, COMMIT,


ROLLBACK
DDL
DDL is a syntax for creating and modifying database objects such as tables,
indexes, and users.

DDL statements are similar to a computer programming language for defining


data structures, especially database schemas.

Common examples of DDL statements include CREATE, ALTER, and DROP.


DDL Example
CREATE TABLE public.profile (
id integer NOT NULL,
userid integer,
CONSTRAINT profile_pkey PRIMARY KEY (id),
CONSTRAINT fk1 FOREIGN KEY (userid)
REFERENCES public."user" (id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
) TABLESPACE pg_default;

ALTER TABLE public.profile


OWNER to postgres;
DROP TABLE public.profile;
More DDL Examples
ALTER TABLE user ADD COLUMN lastname VARCHAR(255) NOT NULL;

RENAME TABLE user TO student;

ALTER TABLE reference DISABLE TRIGGER ALL; // including FK constraints

TRUNCATE books; DELETE from books;

Differences between DELETE and TRUNCATE commands are:

● TRUNCATE is really faster


● TRUNCATE cannot be rolled back
● TRUNCATE command does not invoke ON DELETE triggers
PostgreSQL Data Types
PostgreSQL supports the following data types:

● Boolean
● Character types such as char, varchar, and text.
● Binary, Enumerations types
● Numeric types such as integer, monetary and floating-point
number.
● Temporal types such as date, time, timestamp, and interval
● UUID for storing Universally Unique Identifiers
● Array for storing array strings, numbers, etc.
● JSON, XML stores JSON/XML data
● hstore stores key-value pair
● Special types such as network address and geometric data.
DQL: SELECT
● The SELECT clause, which indicates projected data.
● The FROM clause, which indicates the table(s) to retrieve data from. The FROM clause can include optional
JOIN subclauses to specify the rules for joining tables.
● The WHERE clause includes a comparison predicate, which restricts the rows returned by the query. The
WHERE clause eliminates all rows from the result set where the comparison predicate does not evaluate to
True.
● The GROUP BY clause projects rows having common values into a smaller set of rows. GROUP BY is often
used in conjunction with SQL aggregation functions or to eliminate duplicate rows from a result set. The
WHERE clause is applied before the GROUP BY clause.
● The HAVING clause includes a predicate used to filter rows resulting from the GROUP BY clause. Because it
acts on the results of the GROUP BY clause, aggregation functions can be used in the HAVING clause
predicate.
● The ORDER BY clause identifies which column[s] to use to sort the resulting data, and in which direction to
sort them (ascending or descending). Without an ORDER BY clause, the order of rows returned by an SQL
query is undefined.
● The DISTINCT keyword eliminates duplicate data.
SELECT: the basic order of execution
SELECT: the simplified syntax
SELECT [DISTINCT | ALL] <expression>[[AS] <output_name>][, …]
[FROM <table>[, <table>… | <JOIN clause>…]
[WHERE <condition>]
[GROUP BY <expression>|<output_name>|<output_number> [,…]]
[HAVING <condition>]
[ORDER BY <expression>|<output_name>|<output_number> [ASC | DESC] [NULLS FIRST |
LAST] [,…]]
[OFFSET <expression>]
[LIMIT <expression>];
SELECT: The Execution Algorithm
The logical sequence of operations performed by the SELECT command is as
follows:

1) select all records from all source tables. If there are sub-queries in the
FROM clause, then they are evaluated first;
2) form all possible combinations of these records and discard those for
which the JOIN conditions are not satisfied, and in the case of external
joins, set some fields in such combinations to NULL;
3) filter out combinations that do not satisfy the predicate in the phrase
WHERE;
SELECT: The Execution Algorithm
The logical sequence of operations performed by the SELECT command is as
follows:

4) build groups according to the values of the expressions in the list GROUP
BY;
5) leave only groups that meet the HAVING conditions;
6) calculate expressions in the selection list;
7) exclude duplicate lines if the DISTINCT keyword is present;
8) apply set-theoretic operations UNION, EXCEPT and INTERSECT;
9) sort lines according to the ORDER BY clause;
10) leave only records that meet the conditions in the phrases OFFSET and
LIMIT.
SELECT: simple examples
select * from books; -- n rows

select sum(pages) from books; -- 1 row

select 1;

select 2+2;

select * from A,B (the Cartesian product)

select * from a inner join b on a.id=b.id;

select distinct(*) from a where f1<>f2 order by f1,f2;

select column1[2] from (values ('{1,2,3}' :: int[]) ) as v -- 2


SELECT: special symbols
Special symbols:

- parentheses () are used to specify the order of operations and to group


expressions. Some SQL commands have special meanings. Also used in
the function header;
- square brackets [] are used to select array elements;
- colon : is used to access part of an array; double colon :: is used for type
casting; comma , is used to separate list items;
- a period . is used to separate the schema name, table name, and column
name;
- semicolon ; ends the command;
- an asterisk * denotes all columns in a table or all members of a composite
value.
SELECT: Expressions
SQL statements can contain:

- column names (in most cases);


- constants: 3.14
- operators: + - * /
- parentheses () that specify the order of calculations;
- function calls: substring(), upper(), lower(), now(), date_part(), abs(), round()
- aggregate expressions: SUM(), COUNT(), MAX(), MIN(), AVG()
- scalar subqueries: SELECT (SELECT 1) + (SELECT 2) AS three;
- type casts like: CAST (<value> AS <type>); <value> :: <type>; <type>
'<value>'; <type> (<value>).
- conditional expressions: SELECT CASE WHEN now() > date_trunc('day', now()) +
interval '12 hours' THEN 'PM' ELSE 'AM' END;
SELECT: Expressions examples
SELECT: Expressions examples
SELECT: DISTINCT clause
The keywords DISTINCT and ALL, which can appear immediately after the
word SELECT, are also directly related to the selection list.

If DISTINCT is present, duplicates are removed from the output dataset. If the
word ALL is specified (this is the default mode), then all rows are returned.
SELECT: DISTINCT clause
SELECT: FROM clause
Row sources are specified after the FROM keyword. This part of the query is
called the FROM clause.

You can select data from zero, one or more sources. If there is no source of
strings, then the FROM clause should not be present. The following string
sources are possible:

● table;
● view;
● function;
● subquery;
● VALUES phrase
SELECT: FROM clause
Tables as a source:

One table: select * from user; -- all rows from user

Two tables - JOIN:


SELECT - FROM - JOIN
CROSS JOIN - Cartesian product:

select * from "group" cross join student;

select * from "group", student;

You might also like