Date post: | 14-Jan-2016 |
Category: |
Documents |
Upload: | bruce-hodges |
View: | 245 times |
Download: | 0 times |
Pavel Titenkov ©
SQL
Pavel Titenkov ©
Общий обзорОбщий обзор
• англ. Structured Query Language — «язык структурированных запросов»
• Это наиболее часто используемый язык Это наиболее часто используемый язык для работы с БДдля работы с БД
• SQL SQL работает с множеством языков 4работает с множеством языков 4gl gl
SQL
Pavel Titenkov ©
Используется дляИспользуется для::
• Data ManipulationData Manipulation
• Data DefinitionData Definition
• Data AdministrationData Administration
• All are expressed as an SQL statement All are expressed as an SQL statement or command.or command.
SQL
Pavel Titenkov ©
SQL SQL RequirementsRequirements
• SQL Must be embedded in a programming SQL Must be embedded in a programming languagelanguage
• SQL is a free form language so there is no SQL is a free form language so there is no limit to the the number of words per line or limit to the the number of words per line or fixed line break.fixed line break.
• Syntax statements, words or phrases are Syntax statements, words or phrases are always in lower case; keywords are in always in lower case; keywords are in uppercase.uppercase.
SQL
Not all versions are case sensitive!Not all versions are case sensitive!
Pavel Titenkov ©
SQL is a Relational DatabaseSQL is a Relational Database
• каждый элемент таблицы — один элемент данных
• все ячейки в столбце таблицы однородные, то есть все элементы в столбце имеют одинаковый тип (числовой, символьный и т. д.)
• каждый столбец имеет уникальное имя
• одинаковые строки в таблице отсутствуют
• порядок следования строк и столбцов может быть произвольным
Реляционная модель ориентирована на организацию данных в виде двумерных таблиц. Каждая реляционная таблица представляет собой двумерный массив и обладает следующими свойствами:
Pavel Titenkov ©
DesignDesign
Операторы SQL делятся на:
• операторы определения данных (Data Definition Language, DDL)
• операторы манипуляции данными (Data Manipulation Language, DML)
• операторы определения доступа к данным (Data Control Language, DCL)
SQ
L
Pavel Titenkov ©
Rows describe the
Occurrence of an Entity
Table DesignTable DesignSQL
Name Address
Jane Doe 123 Main Street
John Smith 456 Second Street
Mary Poe 789 Third Ave
Columns describe one characteristic of the entity
Pavel Titenkov ©
Data Retrieval (Queries)Data Retrieval (Queries)
• Queries search the database, fetch info, Queries search the database, fetch info, and display it. This is done using the and display it. This is done using the keywordkeyword SELECT
SELECT * FROM publishersSELECT * FROM publishers
pub_id pub_name address state
0736 New Age Books 1 1st Street MA
0987 Binnet & Hardley 2 2nd Street DC
1120 Algodata Infosys 3 3rd Street CA
•The The ** Operator asks for every column in Operator asks for every column in
the table.the table.
Pavel Titenkov ©
Data Retrieval (Queries)Data Retrieval (Queries)• Queries can be more specific with a few Queries can be more specific with a few
more linesmore lines
pub_id pub_name address state
0736 New Age Books 1 1st Street MA
0987 Binnet & Hardley 2 2nd Street DC
1120 Algodata Infosys 3 3rd Street CA
• Only publishers in CA are displayedOnly publishers in CA are displayed
SELECT *SELECT *from publishersfrom publisherswhere state = ‘CA’where state = ‘CA’
Pavel Titenkov ©
Data InputData Input• Putting data into a table is accomplished Putting data into a table is accomplished
using the keyword using the keyword INSERT
pub_id pub_name address state
0736 New Age Books 1 1st Street MA
0987 Binnet & Hardley 2 2nd Street DC
1120 Algodata Infosys 3 3rd Street CA
• Table is updated with new informationTable is updated with new information
INSERT INTO publishersINSERT INTO publishersVALUES (‘0010’, ‘pragmatics’, ‘4 4VALUES (‘0010’, ‘pragmatics’, ‘4 4thth Ln’, ‘chicago’, ‘il’) Ln’, ‘chicago’, ‘il’)
pub_id pub_name address state
0010 Pragmatics 4 4th Ln IL
0736 New Age Books 1 1st Street MA
0987 Binnet & Hardley 2 2nd Street DC
1120 Algodata Infosys 3 3rd Street CA
Keyword
Variable
Pavel Titenkov ©
Types of TablesTypes of Tables
• User Tables: User Tables: contain information that is contain information that is the database management systemthe database management system
• System Tables: System Tables: contain the database contain the database description, kept up to date by DBMS description, kept up to date by DBMS itselfitself
There are two types of tables which make up There are two types of tables which make up a relational database in SQLa relational database in SQL
Relation Table
Tuple Row
Attribute Column
Pavel Titenkov ©
Using SQLUsing SQL
SQL statements can be embedded into a program SQL statements can be embedded into a program (cgi or perl script, Visual Basic, MS Access)(cgi or perl script, Visual Basic, MS Access)
OROR
SQL
Datab
ase
SQL statements can be entered directly at the SQL statements can be entered directly at the command prompt of the SQL software being command prompt of the SQL software being used (such as mySQL)used (such as mySQL)
Pavel Titenkov ©
Using SQLUsing SQL
To begin, you must first CREATE a database To begin, you must first CREATE a database using the following SQL statement:using the following SQL statement:
CREATE DATABASE database_nameCREATE DATABASE database_name
Depending on the version of SQL being used Depending on the version of SQL being used the following statement is needed to begin the following statement is needed to begin using the database:using the database:
USE database_nameUSE database_name
Pavel Titenkov ©
Using SQLUsing SQL
• To create a table in the current database, use the CREATE TABLE keyword
CREATE TABLE authorsCREATE TABLE authors(auth_id int(9) not null,(auth_id int(9) not null,auth_name char(40) not null)auth_name char(40) not null)
auth_id auth_name
(9 digit int) (40 char string)
Pavel Titenkov ©
Using SQLUsing SQL
• To insert data in the current table, use the keyword INSERT INTO
auth_id auth_name
• Then issue the statement
SELECT * FROM authors
INSERT INTO authorsvalues(‘000000001’, ‘John Smith’)
000000001 John Smith
Pavel Titenkov ©
Using SQLUsing SQL
SELECT auth_name, auth_citySELECT auth_name, auth_cityFROM publishersFROM publishers
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI
000000001 John Smith Taylor MI
auth_name auth_city
Jane Doe Dearborn
John Smith Taylor
If you only want to display the author’s name and city from the following table:
Pavel Titenkov ©
Using SQLUsing SQL
DELETE from authorsDELETE from authorsWHERE auth_name=‘John Smith’WHERE auth_name=‘John Smith’
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI
000000001 John Smith Taylor MI
To delete data from a table, use the DELETE statement:
Pavel Titenkov ©
Using SQLUsing SQL
UPDATE authorsUPDATE authorsSET auth_name=‘hello’SET auth_name=‘hello’
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI
000000001 John Smith Taylor MI
To Update information in a database use the UPDATE keyword
Hello
Hello
Sets all auth_name fields to helloSets all auth_name fields to hello
Pavel Titenkov ©
Using SQLUsing SQL
ALTER TABLE authorsALTER TABLE authorsADD birth_date datetime nullADD birth_date datetime null
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI
000000001 John Smith Taylor MI
To change a table in a database use ALTER TABLE. ADD adds a characteristic.
ADD puts a new column in the table called birth_date
birth_date
.
.
Type Initializer
Pavel Titenkov ©
Using SQLUsing SQL
ALTER TABLE authorsALTER TABLE authorsDROP birth_dateDROP birth_date
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI
000000001 John Smith Taylor MI
To delete a column or row, use the keyword DROP
DROP removed the birth_date characteristic from the table
auth_state
.
.
Pavel Titenkov ©
Using SQLUsing SQL
DROP DATABASE authorsDROP DATABASE authors
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI
000000001 John Smith Taylor MI
The DROP statement is also used to delete an entire database.
DROP removed the database and returned the memory to system
Pavel Titenkov ©
Conclusion
• SQL is a versatile language that can integrate with numerous 4GL languages and applications
• SQL simplifies data manipulation by reducing the amount of code required.
• More reliable than creating a database using files with linked-list implementation
Pavel Titenkov ©
References
• “The Practical SQL Handbook”, Third Edition, Bowman.