You are on page 1of 61

Unit 2: Basic SQL

Pratian Technologies (India) Pvt. Ltd.


www.pratian.com
Overview
 UNIT 1 – Introduction to RDBMS
 Relational DBMS

 UNIT 2 – Introduction to SQL


 DDL – Create, Alter, Drop, Truncate

 UNIT 3 – Data Manipulation Language


 DML – Insert, Update, Delete, Transactions – Commit, Rollback

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Overview
 UNIT 4 – Select Statements
 Select statement – Where clause
 Like, Logical operators, In and between predicates
 Null, Not null, Aggregate functions
 Order by
 Group By

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
UNIT 1

Introduction to RDBMS

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Relational DBMS
 RDBMS is a model in which all data is logically
structured with relations
 Data is stored in tables
 It is a two dimensional table with special properties
Students Table
StudentId Name Age CourseId
1001 Krishna S 19 1
1002 Raghav K 21 2

Courses Table
CourseId Course
1 Basic SQL
2 Excel

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Relational DBMS
 Rows – Tuples [collection of records]
 Each record contains same fields
 Columns – Attributes – Domain specific
 Different types of data exist mainly - Character,
Numeric, Date
StudI Name Age JoinDate Fees CourseI
d d
1001 Krishna S 19 14-MAY- 1000 1
2010
1002 Preethi J 21 15-MAY- 2000 2
2010
1003 Sriram V 21 15-MAY- 1200 1
2010

CourseId Course
1 Basic SQL
Copyright © 2010 Pratian Technologies
2 Excel
www.pratian.com
Basic SQL
Relational DBMS - Properties
 Entries of column and row values have to be single
valued

 Entries of attributes [columns] are of same kind

 No two rows are identical

 Order of rows and columns are unimportant

 Every column has to be uniquely defined

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Relational DBMS – Database Schema
 Organization of information within database for single or
multiple users

 Store of data that describes the content and structure of


physical data store

 It contains various information like data types,


relationships, access controls etc..

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Relational DBMS - Architecture
Users

DATABASE Application Programs/Queries


SYSTEM
DBMS

Software to process queries/programs

Software to access stored data

Stored Data Defn. Stored Database

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Relational DBMS - Users
 Application Programmers
 Responsible for writing application programs that use the
database
 End Users
 Interact with the system from workstations or terminals. A given
end user can access the database via one of the applications
 Administrators
 One who manages the database centrally
 Decides on the type of internal structures and relationships
 Ensures security of the database
 Controls access to data through codes and passwords
 Can restrict views or operations users can perform on database

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Relational DBMS – Data Integrity
 Data integrity
 Refers to wholeness and roundness of the database
 Achieved by using integrity constraints and domain constraints
 Primary Key
 Uniquely identify a particular record
 Foreign Key
 Primary key in one table will be referenced in another table
 CourseId is the foreign key here
Stud_Id Name Age CourseId
1 Krishna 19 1

2 Radha 21 2

CourseId Course
1 SQL
2 Excel
Copyright © 2010 Pratian Technologies
www.pratian.com
Basic SQL
Summary
 Understand database concepts

 Know characteristics of a DBMS

 Understand Relational DBMS concepts

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
UNIT 2

Introduction to SQL

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
What is SQL?

 SQL stands for Structured Query Language

 Simple, powerful and standard data access language


for relational database management systems

 It is a specialized language for updating, deleting and


requesting information from databases

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Standard SQL Statement Groups
Group Statements Description
DQL SELECT DATA QUERY LANGUAGE
Used to get data from database
DML INSERT DATA MANIPULATION
UPDATE LANGUAGE
DELETE Used to add or change database
data
DDL CREATE DATA DEFINITION LANGUAGE
ALTER Used to manipulate database
DROP structures and definitions
TRUNCATE
DAL GRANT DATA ADMINISTRATION
REVOKE LANGUAGE
Used to grant and revoke access
rights to database objects

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Data Types in SQL
Data type Description
CHAR(n) To store fixed length string. Maximum length = 255
bytes
VARCHAR(n) To store variable length string. Maximum length =
255 bytes
TEXT or BLOB To store maximum length of 65535 characters.
Binary Large Objects – Text, images, files etc..
TINYINT If signed: -128 to 127. If unsigned: 0 to 255. You
can specify a width of up to 4 digits.
SMALLINT If signed : -32768 to 32767. If unsigned : 0 to
65535. You can specify a width of up to 5 digits.
INT If signed : -2147483648 to 2147483647. If
unsigned : 0 to 4294967295. You can specify a
width of up to 11 digits.

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Data Types in SQL
Data type Description
FLOAT(M,D) You can define the display length (M) and the
number of decimals (D). Decimal precision can go
to 24 places for a FLOAT.
DOUBLE(M,D) You can define the display length (M) and the
number of decimals (D). Decimal precision can go
to 53 places for a FLOAT.
DATE A date in YYYY-MM-DD format, between 1000-01-
01 and 9999-12-31. For example, December 30th,
1973 would be stored as 1973-12-30
DATETIME A date and time combination in YYYY-MM-DD
HH:MM:SS format, between 1000-01-01 00:00:00
and 9999-12-31 23:59:59. For example, 3:30 in
the afternoon on December 30th, 1973 would be
stored as 1973-12-30 15:30:00

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Creation of Database Objects - DDL
 Table
 Tables are objects which store data
 A table can have a maximum of 1000 columns

 Syntax

 CREATE TABLE table_name


(
{col_name col_datatype [[CONSTRAINT
const_name][col_constraint]]}
[table_constraint],…
)
[AS query]

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Creation of Database Objects - DDL
 Example

 CREATE TABLE Students


(
StudentId int,
Name varchar(100),
JoinDate date
);
 CREATE TABLE Courses
(
CourseId int,
Course varchar(50)
);

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Creation of Database Objects - DDL
 Naming of tables

 Name of the table must begin with a letter A-Z or a-z. It may
contain numerals and the special character _ (underscore)

 It can be 30 characters in length

 It must not be a SQL reserved word

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Specifying Integrity Constraints
 A database is said to be “integrated” if the values in the
database are correct according to a set of rules

 Checking of consistency must be carried out to ensure


data integrity

 The definition of a table may include the specification of


integrity constraints

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Specifying Integrity Constraints

 Types of Constraints

 Column constraints – associated with a single column


 Table constraints – associate with more than one column

 A constraint can be named

 If not named, will be automatically generated by DBMS

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Types of Integrity Constraints
 NOT NULL

 UNIQUE

 PRIMARY KEY

 FOREIGN KEY

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
NOT NULL CONSTRAINT
 User will not be allowed to enter null values

 Example:

 CREATE TABLE Students


(
StudentId int,
Name varchar(100) NOT NULL,
JoinDate date NOT NULL
);

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
DEFAULT CLAUSE
 To specify a default value for an attribute if no value is
given

 Example:

 CREATE TABLE Students


(
StudentId int,
Name varchar(100),
JoinDate date,
City varchar(100) DEFAULT ‘BANGALORE’
);

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
UNIQUE CONSTRAINT
 The keyword UNIQUE specifies that no two records can
have the same attribute value for a column

 Example:

 CREATE TABLE Courses


(
CourseId int,
Course varchar(50) UNIQUE
);

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
PRIMARY KEY CONSTRAINT
 A primary key constraint enables a unique identification of
each record in a table

 Example:

 CREATE TABLE Students


(
StudentId int NOT NULL Auto_Increment,
Name varchar(50),
JoinDate date,
PRIMARY KEY (StudentId)
);

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
FOREIGN KEY CONSTRAINT
 This constraint specifies a column or list of columns as a
foreign key of the referencing table
 Referencing table is called “Child table”, referenced table
is called “Parent table”

 Example:

 CREATE TABLE Students


(
StudentId int,
Name varchar(100),
CourseId int NOT NULL,
Foreign Key (CourseId) REFERENCES Courses(CourseId)
);
Copyright © 2010 Pratian Technologies
www.pratian.com
Basic SQL
MODIFYING A TABLE
 The ALTER command is used to modify an existing table

 Syntax:

 ALTER TABLE table_name


[ADD (col_name col_datatype col_constraint,..)] |
[MODIFY existing_col_name new_col_datatype new_constraint] |
[ADD (table_constraint)] |
[DROP CONSTRAINT constraint_name] |
[DROP COLUMN existing_col_name];

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
MODIFYING A TABLE
 ADD clause
 The ADD clause is used to add a column or a constraint to an
existing table

 MODIFY clause
 The MODIFY clause is used to modify existing columns of a table

 DROP clause
 DROP clause is used to remove columns or constraints from a
table

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
MODIFYING A TABLE
 Example:

 ALTER TABLE Students ADD Location varchar(100) DEFAULT


‘BANGALORE’;

 ALTER TABLE Courses MODIFY Course varchar(100) UNIQUE;

 ALTER TABLE Courses CHANGE Course CourseName


varchar(100) UNIQUE;

 ALTER TABLE Students DROP JoinDate;

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
DROP A TABLE
 To remove the definition of a table from the database
DROP TABLE command is used

 Example:

 DROP TABLE Courses;

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Summary
 Understand SQL as the standard language for interacting
with relational database

 Know the type of SQL statements

 Understand DDL statements to create relational tables

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
UNIT 3

Data Manipulation

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
DATA MANIPULATION
 DML – Data Manipulation Statements are used to make
changes to the data stored in a table

 The manipulations that can be performed on a table are


 Add
 Data is inserted into table using INSERT statement
 Update
 Any modifications to table data are made using
UPDATE statement
 Delete
 Table data is deleted using DELETE statement

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
INSERT STATEMENT
 INSERT statement is used to add new data into the table

 Syntax:
 INSERT INTO table_name
[(col_name1, col_name2,…)]
{VALUES (value1, value2, …) | query };

 Example:
 INSERT INTO Courses (CourseId, Course)
VALUES (2, ‘EXCEL’);

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
INSERT STATEMENT
 Insert using query output
 Example: [CoursesOffered is another table with fields as Courses]

 INSERT INTO Courses (CourseId, Course)


SELECT * FROM CoursesOffered

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
INSERT STATEMENT – GENERAL RULES
 Values should match data type of the respective columns

 Number of values should match the number of column


names mentioned

 All columns declared as NOT NULL should be supplied


with a value

 Character strings should be enclosed in quotes

 DATE values should be enclosed in quotes

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
UPDATE STATEMENT
 Update statement is used when we need to modify data in
a table

 Syntax:
 UPDATE {table_name | alias}
SET col_name = value |
col_name = (SELECT Statement)
[WHERE Condition];

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
UPDATE STATEMENT
 Update all rows
 UPDATE Students
SET JoinDate = ’2010-10-17’;

 Update only certain rows


 UPDATE Students
SET JoinDate = ’ 2010-10-17’
WHERE Name = ‘Krishna’;

 Update multiple columns


 UPDATE Students
SET JoinDate = ’ 2010-10-17’, Name = ‘Krishna S’
WHERE StudentId = 2;

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
DELETE STATEMENT
 DELETE statement is used to delete rows from a table

 Syntax:
 DELETE [FROM] {table_name | alias }
[WHERE Condition];

 Delete all rows from table


 DELETE FROM Students;

 Delete particular row from table


 DELETE FROM Students WHERE StudentId = 2;

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Summary
 We know how to manipulate data in a table using DML
commands

 Know how to save or undo changes made to table data

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
UNIT 4

SELECT STATEMENT

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
SELECT STATEMENT
 We will be looking at the following

 SELECT STATEMENT
 How to retrieve data from tables
 Column aliases
 Where clause
 Pattern matching LIKE
 SELECT STATEMENT - more options
 Logical operators – AND, OR, NOT
 IN
 BETWEEN
 IS NULL / IS NOT NULL
 GROUP BY / ORDER BY

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
SELECT STATEMENT
 Syntax:

 SELECT [ALL | DISTINCT ] { * | col_name,..}


FROM table_name alias
[WHERE expr1]
[CONNECT BY expr2 [START WITH expr3]]
[GROUP BY expr4] [HAVING expr5]
[UNION | INTERSECT]
[ORDER BY expr | ASC | DESC];

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
COLUMN ALIAS AND DISTINCT
 Giving alias
 SELECT StudentId, Name, JoinDate “JoiningDate”
FROM Students;

 DISTINCT – To get unique values


 SELECT DISTINCT Name FROM Students;

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
WHERE CLAUSE
 WHERE Clause
 Where clause is used to do selective retrieval of rows
 Rows which meet search condition are returned
 WHERE <search condition>

 List of Operators
 = Equal to
 <> Not equal to
 < Less than
 > Greater than
 <= Less than equal to
 >= Greater than equal to

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
WHERE CLAUSE
 To get all rows where join date is equal to a date
 SELECT * FROM Students WHERE JoinDate = ’ 2010-10-17’;

 To get all rows where StudentId is greater than 2


 SELECT * FROM Students WHERE StudentId > 2;

 To get all rows where Join date is greater than or equal to


a date
 SELECT * FROM Students WHERE JoinDate >= ’ 2010-10-17’;

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
LIKE PREDICATE
 The pattern contains a search string along with other
special characters % and _

 An underscore(_) in the pattern matches exactly one


character

 A percent sign (%) in the pattern can match zero or more


characters
 It cannot match a NULL

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
LIKE PREDICATE
 To list all students whose name begins with ‘K’
 SELECT Name
FROM Students
WHERE Name LIKE ‘K%’;

 To list all students whose name begins with ‘K’ and third
letter ‘I’
 SELECT Name
FROM Students
WHERE Name LIKE ‘K_I%’;

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
LOGICAL OPERATOR
 A logical operator combines the results of two component
conditions to produce a single result based on them or
invert the result of a single condition

 NOT – Returns true if condition is false, returns false if


condition is true

 AND – Returns true if both component conditions are true,


returns false if both component conditions are false

 OR – Returns true if either component condition is true,


returns false if both component conditions are false

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
LOGICAL OPERATOR
 NOT
 SELECT Name FROM Students WHERE NOT StudentId = 2;

 AND
 SELECT Name FROM Students
WHERE StudentId > 1 AND JoinDate >= ‘2010-10-17’;

 OR
 SELECT Name FROM Students
WHERE Name = ‘Krishna’ OR StudentId = 2;

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
IN PREDICATE
 To select rows from defined set of values

 SELECT *
FROM Students
WHERE Name IN (‘Krishna’, ‘Radha’);

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
BETWEEN PREDICATE
 To retrieve rows which meets the range of values given

 SELECT * FROM Students


WHERE JoinDate
BETWEEN ’ 2010-10-17’ AND ‘2010-10-20’;

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
NULL PREDICATE
 NULL predicate is used to check if an attribute or a
column is null.
 Col_name = NULL cannot be done

 IS NULL
 SELECT * FROM Students WHERE JoinDate IS NULL

 IS NOT NULL
 SELECT * FROM Students WHERE Name IS NOT NULL

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
AGGREGATE FUNCTIONS
 Produces a single value for an entire group
 Functions are
 COUNT()
 Produces the number of rows query has selected
 AVG()
 Produces the average of all selected values of a given column
 MAX()
 Produces the largest of all selected values of a given column
 MIN()
 Produces the smallest of all selected values of a given column
 SUM()
 Produces the arithmetic sum of all selected values of a given
column

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
GROUP BY
 The GROUP BY clause is used to group selected rows
and return a single row of summary information

 Each group of rows are based on the values of the


expression(s) specified in the GROUP BY clause

 Grouping can be done on multiple columns

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
GROUP BY
 Example:
 SELECT CourseId, sum(Fees)
FROM Students
GROUP BY CourseId

 SELECT CourseId, sum(Fees)


FROM Students
GROUP BY CourseId
HAVING Name IS NOT NULL

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
ORDER BY
 ORDER BY clause is used to sort records

 The sort is done on the column in either ascending or


descending order. [ASC default]

 Example:
 SELECT * FROM Students
ORDER BY NAME

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Summary
 Know how to use the SELECT statement to retrieve data
from a table

 Know the options to be used with SELECT statement for


conditional data retrieval

 Know how to group data based on a value

 Know how to sort data

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL
Question Time
Please try to limit the questions to the topics discussed during the session. Thank you.

Copyright © 2010 Pratian Technologies


www.pratian.com
Basic SQL

You might also like