Introduction to SQL
Structured Query Language (SQL)By
P.D. Krolak & M.S. KrolakCopyright 2001
SQL What is it? SQL is a natural language like, ANSI
standard for interfacing database systems.
Developed in the 70’s by IBM. SQL has been revised several times and
is supported by almost all commercial and/or widely used databases.
Designed to be similar to a declarative sentence and to be used by the non programmer.
SQL Statement SQL has a simple natural language
structure. Starts with a verb, followed by a
series of clauses and ends with “;”. Uses a small set of reserved words. SQL is used to communicate with
the relational database thru a standard API.
SQL Reserve Words Alter And As Create Cross Join Delete Drop From
Full Join Group by Insert Into Join Left Join Like Limit
SQL Reserve Words: (continued) On Or Order By Right Join Select Where
SQL has Two Parts Data Creation Language (DCL) to
create database objects. Data Manipulation Language (DML)
to manipulate the of data.
SQL SQL is case insensitive. SQL object names are case
sensitive. SQL objects name -- databases,
tables, columns, and passwords.
SQL SQL is used to:
create the database’s objects, to store and edit the data, to form queries, and to allow the DB system’s
administrator to: establish the users, define their privileges, and to provide maintenance.
SQL Data Creation Language
Basic Database Building Blocks
Create DatabaseCreate IndexCreate Table
SQL Database Creation Action -- Creates the database
object. Syntax –Create Database database_name ; Example:
Create Database ClassDatabase;
SQL Table Creation Syntax Syntax --Create Table table_name ( col1 type
restriction, col2 type restriction, … );
Each column name should be unique, start with a letter and be made up of letters, numbers, and “_”, and not use a reserved word.
Data types define what type of data object maybe stored in the column
Restrictions or constraints limit what kinds of information may be stored, e.g. unique or non null.
SQL Data Types There a wide variety of data types found
in SQL not all of whom are supported in the various commercial systems.
Common data types are integer, real, character, text, date and time, and binary (blob).
Not every DBM system supports every data type so read the manual.
MySQL supports the following data types
MySQL supports a wide variety of data types:
1. Integer (signed and unsigned) 1-8 byte2. Float (real) 4-8 byte3. Datetime4. Char (string) including fixed and
variable length, case sensitive, binary (blob)
5. Enumerated and set
MySQL supports the following integer data typesInteger Data Type Description
TinyInt(length) Unsigned Byte --1
Int1(length) Signed Byte --1
Smallint(length) Unsigned Byte --2
Int(length) Signed Byte --2
MediumInt(length) Unsigned Byte --3
Int3(length) Signed Byte --3
MiddleInt(length)
Int(length) Unsigned Byte --4
Integer(length) Signed Byte --4
Int4(length)
BigInt(length) Unsigned Byte --8
Int8(length) Signed Byte --8
MySQL supports the following numeric (float) data types
Numeric Data Type Description
Float Floating Point Number –4 Bytes
Float(length, decimal)
Float4(length, decimal)
DoublePrecision(length,decimal)
Double Precision Floating Point – 8 Bytes
Double(length,decimal)
Float8(length,decimal)
Foat8
MySQL supports the following DateTime data typesDateTime Data Type Description
Timestamp(Length) Timestamp updates with update, null stores current
Date Date value yyyy-mm-ddAssign null stores current
Time HH-MM-SS time
Datetime Stores date & time
Year Year in either YYYYY or YY format
MySQL supports the following Character data typesCharacter Data Type Description
Char(length) Fixed character size
Binary(length) Case Sensitive
VarChar(length) Varaible character, length maxium
VarBinary(length) Same as above and Case Sensitive
TinyIext Text up to 256 char
TinyBlob As above and Case Sensitive
Text(length) Text Field 64Kb
Blob A binary field up to 64Kb
MediumText Up to 16Mb
MediumBlob Up to 16MB
LongText Up to 4Gb
LongBlob Up to 4Gb
MySQL supports the following data types
Data Type Description
Enum An enumerated list of values
Set A set of predefined values that can be entered as comma separated list or as integer that represents the binary value for the value
Data Definitions
SQL Alter Action – To alter the definition of
the database objects. Syntax – Alter [Ignore] Table table_name
Specification [, Specification]
SQL Alter Specifications A few of the allowed specifications:
Add [Column] column_name (type, )[First or After column_name]
Add Index [index_name] (column_list) Add Primary Key (column_list) Add Unique [index_name] (column_list) Alter [Column] column_name {Set
Default default_value or Drop Default}
SQL Alter Specifications (cont.) More of the allowed specifications:
Drop [Column] column_name Drop Primary Key Drop Index index_name Modify [Column] create definition Rename new_name
SQL Alter Ignore The Ignore option causes rows with
duplicates in unique keys to be deleted. If no duplication, then no change.
SQL Describe Action – give the details of columns
in a selected table. Syntax –Describe table_name column_names
Describe Example
SQL Drop Action – Drops, i.e. deletes the
object. This is a non recoverable action so use cautiously.
Syntax – Drop Database [If Exists]
Database_name; Drop Table [If Exists] Table_name ;
SQL Explain Action – will display query for
select as in the show clause. Syntax –Explain Select_Query OR table_name
SQL Flush Action – Clears out the cache
memory Syntax –Flush flush option1 [, flush option2 ,
…];
SQL Flush options
Option Description
Hosts Clear only if IP address of host change
Logs Closes logs
Privileges Use after changes to the user privileges
Tables Close tables
Status Reset system status =0
SQL Show Action – Show the data in the
result set. Syntax –Show parameter;
Show Parameter The following parameters are used:
Columns From table_name Database_names Grants For user_names Index From table_names Process_list -- list running processes Status
Show Parameter (continued)
Tables From database_name Tables Status From database_name Variables – system variables
SQL Use Action – sets the active database. Syntax – Use database_name;Example –Use pizza_group3;
SQL Key Concepts
Keys are fundamental to creating a relational database.
SQL Primary Key Each row of a table will have a
primary key – a column or collection of columns that uniquely identifies the row. Thus each row will have a unique key. If two or more rows have the same key SQL will report an error.
SQL Multiple Column Keys
SQL Foreign Key A foreign key is a primary key in
another table. For instance, the Student Id number maybe the primary key in the table Student while it is a foreign key in the Class_roster.
SQL Index Each table’s rows need to be
unique, i.e. needs to have a unique primary key.
One method to achieve this is to give each row a row_id or numeric index. This index is auto-incremented every time a new row is inserted in the table.
SQL Data Manipulation Language (DML)
The DML allows the user to insert, query, and edit the data. The ability to form queries and to generate reports is the heart of any Information System
SQL Data Manipulation Insert records into the table. Update data within records. Delete records from tables. Select records from the table(s).
SQL Insert Action – Insert data into the table. Syntax –Insert [delayed|low priority] [into]
Table [(column, … ,)] Values (value, …,) ;
Example –Insert students (first, last, email, user-
id) values (clyde, smith, [email protected], csmith);
SQL Insert Delayed or Low Priority Options Delayed – delay action until table
is free. Will also bundle actions. Low Priority – delay action until the
table is not in use
SQL Update Action – Updates, changes, the selected
data without changing the definition of the table.
Syntax –Update table Set column=value,… [Where
Clause]; Example –Update Student Set user-id=cjsmith Where
first=clyde and last=smith;
SQL Update Set Clause Action – Set the column(s) to the
assigned value(s) Syntax –Set columnk =valuek
columnm=valuem, …
SQL Delete Action – deletes rows from table that
match the Where clause. Syntax –Delete From table [Where clause] ;If no Where clause, all the data is deleted
from the table. Example –Delete From Student Where user-
id=cjsmith;
Constructing the SQL Query
Select Statement1. Where Clause2. Group By Clause3. Having Clause4. Order By Clause
SQL Select Action – Select column(s) from the
table(s), if the row satisfies the clauses of the select. The row is said to be matched and is retained.
The resulting collection of rows is called the result set.
SQL Select Syntax – Select [All|Distinct] List_of_Columns
From List_of Tables [Where Clause] [Group By Clause] [Having Clause] [Order Clause]
SQL Select The option All specifies select all
the rows and is the default choice. The option Distinct specifies that
only those rows that contain unique values For the List_of_Columns will be selected, i.e. no duplicates
SQL Select List_of_Columns If the List_of_Columns, (column1, …), is
selected from more than one table, then they must be fully qualified. This is done by specifying the Table_name.Column_name. Note the dot between the table and the column.
* is used to specify all of the columns in the table.
SQL From List_of_Tables The From List_of_Tables, table1, …,
specifies the table(s) from which the column(s) will be taken.
When List_of_Tables involves more than one table, it is referred to as a Join.
SQL Where clause Action – Selects the rows based on
conditions or constraints formed through logical propositions.
An example of a condition is:Last=‘smith’The logic operators AND, OR, NOT
can also be used.First =“clyde” AND Last=“smith”
SQL Where clause (continued) An example of a compound logic
condition is:Using the logic operators AND, OR,
NOTFirst =“clyde” AND Last=“smith”Would select all records of students
named clyde smith
SQL Comparison Predicates
A comparison predicate is used by a Where clause to compare values. If the comparison is true the row is retained.
SQL Relational Operators
Symbol Operator
= Equal
<> or != Not Equal
< Less Than
> Greater Than
<= Less Than or Equal
>= Greater Than or Equal
SQL Like Retrieves rows if a substring is
located in a string. % represents an arbitrary string of
letters, numbers, and punctuation. The underscore, “_” matches a single
character.
SQL Like (continued) Syntax –Column Like ‘Substring%’ matches if the Substring starts the
String.Column Like ‘%Substring’ matches if the Substring ends the String.Column Like ‘%Substring%’ matches if the Substring is in the
String.
SQL Not Like Action – If the substring does not
match the contents of the column then the row is matched.
Syntax – Column Not Like ‘_substring’ Example –User_id NOT LIKE ‘_smith’
SQL IN IN is true if the column is in the list. Syntax –Value In (Value1, …) Example:Color IN (red, green, blue)If Color is red or green or blue then
return 1 else return 0
SQL Not IN Definition: Not IN is true if the
column is Not In the list. Syntax –Value Not In (Value1, …) Example:Color Not IN (red, green, blue)If Color is red or green or blue then
return 0 else return 1
SQL Between Function is true if the value is >=
lower_ value and <= upper_value. Syntax –value Between
(lower_value,upper_value)5 Between (2, 10) returns as true or
1
SQL IS Null Action – the predicate is matched if
the value is Null. Syntax –value IS Null
SQL IS Not Null Action – the predicate is matched if
the value is Not Null. Syntax –value IS Not Null
SQL All, Some, Any
SQL Exists Action – returns a true value if the
sub select result set returns at least on row.
Syntax --
SQL Unique Action – Similar to Exists it is used
only with a sub select. It is true only if the rows in the result set are unique.
Syntax --
SQL Overlaps Action – tests for time interval
overlaps to detect conflicts in schedules, etc.
Syntax –time_interval1 Overlaps time_interval2
Time intervals may be specified as: A start time + time interval A start time end time
SQL MATCH
Conditional Expressions
Conditional expressions are slightly more complicated expressions than those we have looked at previously.
SQL Case Expression It is similar to a Case statement found in
many programming languages but it is an expression and NOT a statement.
Action – A case expression takes a value and if it matches the when expression performs the then ..
If the result option is not defined the Case returns a Null if the Case is not matched.
SQL Case Expression syntax
SQL Case syntax (continued)
SQL Cast Expression Action – Syntax --
SQL Coalesce Function Action – Returns the first Non Null
value from an array. Syntax –Value Coalesce (value1, ….. )
SQL Select Example Queries
Select is a fundamental statement and deserves an
extensive set of examples to illustrate its many options.
SQL Select ExampleDisplay of the guest book’s visitors
Table output from MySQL & phpmyadmin
SQL Select – A more complex example:Select using Where, Order, Limit Clauses
Note: Where clause’s use of Like and Is Not Null
SQL Joins
Joins are fundamental to queries in relational DBMS. The location of data in unique cells forces the query to select data from multiple tables.
SQL Aliasing or the As Clause Action – allows for the substitution
of a short mnemonic for a longer database object name. Particularly useful in situations that
require the object be fully qualified such as joins.
SQL uses a dot notation to indicate how the object is contained in the database.
SQL Aliasing (continued) Syntax –Very.long.name As Short_name Example --Select s.first s.last gb.grade From
Student As s GradeBook As gb where s.student_id=gb.student_id;
SQL Aliasing (continued) Note the As is often dropped
database object in its long form is followed by a space and the short form
Using the previous example --Select s.first s.last gb.grade From
Student s GradeBook gb where s.student_id=gb.student_id;
SQL Cross Join Action – the Cross Join or Cartesian Join
takes every record of one table and joins it with every record of all the other table(s), i.e. the Cartesian product. This is a huge result set an is not
often used or useful. Syntax –Select List_of Columns From table_name
Cross Join List_of_Tables;
SQL Inner Joins Action – The join uses a Select from with
multiple tables and a where clause to filter the rows. The inner join produces the same outcome with a different syntax and uses the On clause instead of the Where clause.
Syntax –Select * From Table1 As T Inner Join Table2
As TT On (T.id =TT.T_id);
SQL On Clause used with Inner Join Action – the ON clause when used
in the Inner join is used in place of the Where Clause. It performs the same task of filtering
the rows of the Select. If the On Clause is true the Left Table
and the Right table are retained and rejected if False.
SQL On Clause used with Inner Join (continued) Syntax – Select List_of_Columns From
Left_table Inner Join Right_table On(Left_table_id = Right_table_id);
SQL Using Clause Action – Used in place of ON
Clause where the column names are the same in both tables and the values are equal. This is a short cut.
Syntax –Using (column_name1 …)
SQL Outer Joins Outer Joins are based on using two
tables the first is called the left and other is called the right. There are three types of outer joins:
1. Left Outer Join2. Right Outer Join3. Full Outer Join
SQL Left Outer Join Action – The Left_table is matched
to the Right_table. The Left and Right rows are retained
if there is a match. The Left row is retained if there is no
match and the Right row is Null filled.
SQL Left Outer Join Syntax Syntax --
SQL Right Outer Join Action – The Right_table is
matched to the Left_table. The Left and Right rows are retained
if there is a match. The Right row is retained if there is no
match and the Left row is Null filled. Symmetric to the Left Outer Join.
SQL Right Outer Join (NOTE)
Many RBDMS do not support the Right Outer Join since one has only to exchange the choice of Right and Left Table and perform the Left outer Join.
SQL Right Outer Join Syntax Syntax –Select List_columns From right_table Right Outer Join left_table
On[..] ;
SQL Full Outer Joins Action – The Full Outer Join performs
both a Left Outer Join and Right Outer Join. The filter on the match is to retain the
Left and Right row. For the unmatched rows:
The unmatched Left row is retained with the Right Row Null Filled.
Similarly for the unmatched Right row.
SQL Full Outer Joins Syntax –
SQL the On Clause is used with the Outer Joins The On Clause is used with the
Outer Joins. As in the Inner Join the ON acts like the Where Clause when the Right and Left Tables match.
SQL On Clause used with Inner Join (continued)ON Clause Used With .. Action When match is not
found does not follow Where Clause
Left Outer Join Left row retained and Right row is filed with NULLs.
Right Outer Join Right row retained and Left row is filed with NULLs.
Full Outer Join Both the Right and Left rows that are not matched are retained and the other row is Null filled.
SQL Join Remarks Since there can not be an Left, Right, or
Full Inner Join, it is permitted to drop the word and use Left Join, Right Join, or Full Join.
The Where Clause is used with the older form of the Join instead of the ANSI SQL92 form Inner Join.
ANSI SQL92 -- When using the Inner Join the use of of the Where Clause will generate an error.
SQL Union Joins
SQL Group By Clause Action – Takes all the rows that that
have data in specific column(s) and will allow aggregation functions to be preformed on them.
Syntax –Group By column_nameGroup By column_name_list
SQL Having Clause Action – Having is used to specify the
rules for choosing rows for the group. Chose those rows having satisfying the specified conditions. Having Clause follows Group By
Syntax –Having Specified_Conditions Example –Having grade_point >= 3.8
SQL Limit Action – the statement is applied
only to the first n occurrences (rows) that match. If there are two values specified the first, start <= n, results in the rejection of the first start occurrences.
Syntax –Limit (n)Limit (start, n)
SQL Order By Clause Action – is an option to display the
query results in ascending or descending order based on specified column(s).
Syntax –Order By Column_List [Asc |Desc]Here Asc is ascending order -- the
default and Desc is descending order.
SQL Functions
SQL supports a large collection of built in functions. It also allows user defined functions.
SQL Value Functions
1. String2. Numeric3. Datetime
SQL String Value Functions
SQL String Value FunctionFunction Description
Substring
Upper
Lower
Trim
Translate
Convert
SQL Numeric Value Functions
SQL Numeric Value FunctionsNumeric Function Description
Position
Character Length
Octet_length
Bit_Length
Extract
SQL Datetime Value Functions
SQL Datetime Value Functions
Datetime function Description
Current_Date
Current_time
Current_timestamp
SQL Expressions
SQL Value Expressions
1. String2. Numeric3. Datetime4. Interval5. Conditional
SQL Aggregate Functions
Aggregate functions are used to summarize the results of a query. The aggregate function is applied to either the full set of rows or a subset based on the Where Clause.
SQL Aggregation Functions:A partial list.Function Description: The operation
is applied to the column of the selected rows
Sum() Sums the numeric values of the column
AVG() Computes the average
MAX() Finds the maximum value
MIN() Finds the minimum.
COUNT() Counts the number of rows selected.
SQL An Example of the Aggregate Function Consider a sales manager who
wants the value of orders placed by each customer in the database.
Select customer_name.c sum(order_value.o) From customers as c and orders as o
where cust_id.c =cust_id.o Grouped By cust_id.o;
SQL User Defined Functions SQL allow the user to create their
own functions and to add them to the function library.
SQL Views
Views are database objects similar to tables but do not have an independent existence.
SQL Setting the Database’s Security
Database security is critical to the success of any serious application. The database administrator must manage the access to critical functionality and data.
SQL Privileges
SQL Grant Action – Establish the access rights
of the database user. Syntax –Grant privilege [column_list)]
[.privilege [column_list)] …] On {table} To user
[Identified By ‘password’] [, user Identified By ‘password’ …] [With Grant Option]
SQL Revoke Action – Revoke removes privileges
from a user using the Grant syntax. The Revoke must be done by some one
holding the Grant privilege to do so. Syntax –Revoke privilege [column_list)]
[.privilege [column_list)] …] On {table} To user
Advanced Issues:
Databases are not all identical in their capabilities. The following are a few features of SQL that are not supported by many DBMS and MySQL in particular.
SQL Transactions
Transactions allow the user to group two or more statements together.
SQL Transactions Not all Database systems support
the transaction concept. Action – The transaction group is
processed as a single thread with logic to allow the statements to “rollback the executed statements to the original state before the transaction.”
SQL Transaction Concept Think of transactions like updating a
column, taking an action on the update, and then closing the table.
What would happen if you phoned a friend, the phone rings but no one answers, you hang up but the charge log database did not get the message and continues to charge you.
SQL Transactions MySQL does not support
transaction as of now. A partial work around is possible
MySQL Transaction Work Around MySQL uses a Lock Table concept
to prevent corruption of the data. MySQL can not do a “Roll Back”
SQL Triggers
Triggers are a group of statements that are execute when a value or condition is true.
SQL Triggers MySQL does not support triggers!! There is no effective work around
using MySQL
SQL Subselects
Subselects are occur when the data you want to select requires a first step to determine and aggregate value or condition before the select can proceed.
SQL Subselect example Consider the query that a sales
manager might make – select customers who ordered more twice the average.
SQL below will NOT work due to lack of value Avg(order)
Select customer order from Customers where order> 2*Avg(order);
SQL Subselect Correct way to form the SQL Statement Select customer order Table
customers where order>2*(Select Avg(order) From order);
Here we first use the sub select to aggregate the orders and compute the average value. Then we perform the Select to find orders that exceed twice the average order value.
SQL Subselects Concept
SQL workarounds for RDBMS that don’t support subselects MySQL does not support
subselects. An effective work around --
Create a temporary table using the result set of the subselect step and then,
Perform the desired select against the temporary table.
SQL References Jager, R.J., Reese, G., King, T.,
“MySQL & MSQL”, O’Reilly Press (1999)
Maslakowski, M., Butcher, T., “Teach Yourself MySQL in 21 Days”, SAMS (2000)
Taylor, A. G., “SQL For Dummies”, IDG Books, 3rd Edition, (1998)