0% found this document useful (0 votes)
19 views

3.1_SQL (1)

This document provides an overview of SQL, including its definition, data types, and commands for data definition and constraints. It explains the structure of SQL queries, including the SELECT statement for data retrieval and the use of constraints like PRIMARY KEY and FOREIGN KEY. Additionally, it covers various data types, including numeric, character strings, and Boolean, along with examples of creating tables and specifying constraints.

Uploaded by

nainitharao.b
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

3.1_SQL (1)

This document provides an overview of SQL, including its definition, data types, and commands for data definition and constraints. It explains the structure of SQL queries, including the SELECT statement for data retrieval and the use of constraints like PRIMARY KEY and FOREIGN KEY. Additionally, it covers various data types, including numeric, character strings, and Boolean, along with examples of creating tables and specifying constraints.

Uploaded by

nainitharao.b
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Khateeja Ambareen

Assistant Professor
Dept. of CSE- AIML
ATMECE, Mysuru
Database Management
Systems
Module – 3
SQL
Introduction

The name SQL is presently expanded as Structured Query Language.


Originally, SQL was called SEQUEL (Structured English QUEry Language)
and was designed and implemented at IBM Research.
SQL is the standard language for commercial relational DBMSs.
SQL Data Definition and Data Types
 SQL uses the terms table, row, and column for the formal relational model terms
relation, tuple, and attribute, respectively.
a schema is called a database

The main SQL command for data definition is the CREATE statement, which can be
used to create schemas, tables (relations) as well as other constructs such as views,
assertions, and triggers.

Schema and Catalog Concepts in SQL:


 An SQL schema is identified by a schema name and includes an authorization
identifier to indicate the user or account who owns the schema.

Schema elements include tables, constraints, views etc.


SQL Data Definition and Data Types

A schema is created via the CREATE SCHEMA statement,


Alternatively, the schema can be assigned a name and authorization
identifier.

CREATE SCHEMA DATABASE_NAME ;


OR
CREATE DATABASE DATABASE_NAME
SQL Data Definition and Data Types
 The CREATE TABLE Command in SQL
 The CREATE TABLE command is used to specify a new relation(table) by
giving it a name(table_name) and specifying its attributes(columns) and
initial constraints.
The attributes are specified first, and each attribute is given a name, a data
type and possibly attribute constraints, such as NOT NULL.
 The key and referential integrity constraints can be specified within the
CREATE TABLE statement after the attributes are declared, or they can be
added later using the ALTER TABLE command.
we can explicitly attach the schema name to the relation name(table name),
separated by a period.
CREATE TABLE COMPANY . EMPLOYEE
rather than
CREATE TABLE EMPLOYEE
SQL Data Definition and Data Types
SQL Data Definition and Data Types
• All examples discussed below refer to the COMPANY database shown
here.
SQL Data Definition and Data Types

Base tables (or base relations): The relations declared through CREATE TABLE
statements.

 This means that the table and its rows are actually created and stored as a file by the
DBMS.
Virtual tables : does not have their data stored as a file.

They depend on base tables to display the data.

Syntax: create view viewname AS QUERY


create view students_view AS
select student_id , std_lastname from students;
To access the view:
Select * from students_view;
SQL Data Definition and Data Types
Attribute Data Types :
Numeric
character string
bit string
Boolean
Date
time.
Numeric data types: integer numbers of various sizes (INTEGER or INT)

 Formatted numbers can be declared by using


DECIMAL(i, j)—or DEC(i, j) or NUMERIC(i, j) –
where i, the precision, is the total number of decimal digits and
 j, the scale, is the number of digits after the decimal point.
The default for scale is zero

Character-string data types


 fixed length-CHAR(n) or CHARACTER(n), where n is the number of characters
 varying length-VARCHAR(n) or CHAR VARYING(n) or CHARACTER VARYING(n)
where n is the maximum number of characters.
SQL Data Definition and Data Types
 BLOB is a Binary Large Object which can hold anything you want including
images and media files.
Anything stored as a binary file.
The data type called BINARY LARGE OBJECT or BLOB is available to specify
columns that have large binary values, such as images , documents etc.

A Boolean : values of TRUE or FALSE.


In SQL, because of the presence of NULL values, a three-valued logic is used,
so a third possible value for a Boolean data type is UNKNOWN.

The DATE data type has ten positions, and its components are YEAR, MONTH, and
DAY in the form YYYY-MM-DD.

The TIME data type has at least eight positions, with the components HOUR,
MINUTE, and SECOND in the form HH:MM:SS.
SQL Data Definition and Data Types

• A query containing all the datatypes


Create table employee(
Emp_id int,
Emp_name varchar(20),
SSN char(9),
Dob date,
Salary decimal(10,2),
Emp_image blob,
Has_passport Boolean);
SQL Data Definition and Data Types

• A timestamp data type (TIMESTAMP) includes the DATE and TIME fields .

• Literal values are represented by single-quoted strings preceded by the


keyword TIMESTAMP, with a blank space between data and time;

• TIMESTAMP ‘2014-09-27 09:12:47.648302’.

CREATE TABLE test_timestamp (t1 TIMESTAMP);

INSERT INTO test_timestamp (t1) VALUES('2008-01-01 00:00:01’);


SQL Data Definition and Data Types
 It is possible to specify the data type of each attribute directly or
alternatively, a domain can be declared, and the domain name can be used
with the attribute specification.

 For example, we can create a domain SSN_TYPE by the following statement:

CREATE DOMAIN SSN_TYPE AS CHAR(9)

Create table person (


SSN SSN_TYPE,
Person_Name Varchar(50));
CONSTRAINTS

• PRIMARY KEY
• NOT NULL
• CHECK
• DEFAULT
• UNIQUE
• FOREIGN KEY
Student (sid,Sname,cid)
PK FK
Course(cid,cname)
PK

CREATE TABLE STUDENT(


Sid integer,
Sname varchar(30),
Branch varchar(20),
Percentage float NOTNULL,
Age integer,
College varchar(20) Default ‘ATME’,
Contact integer UNIQUE,
PRIMARY KEY(Sid)
CHECK (Age>18));
Student (sid,Sname,cid)
PK FK
Course(cid,cname)
PK
CREATE TABLE Course(
cid integer,
cname varchar(30),
Primary key (cid));

CREATE TABLE Student


Sid Integer,
Sname Varchar(30),
cid integer,
Primary Key (Cid),
Foreign key cid References Course (cid));
Specifying Constraints in SQL
 Specifying Attribute Constraints:
Default and NOT NULL Constraints:
SQL allows NULLs as attribute values, a constraint NOT NULL may be
specified if NULL is not permitted for a particular attribute.
It is also possible to define a default value for an attribute by appending
the clause DEFAULT to an attribute definition.

CREATE TABLE Persons (


ID int NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Mysore');
Specifying Constraints in SQL
CHECK Clause:
Another type of constraint can restrict attribute using the CHECK
clause.

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18));
Specifying Constraints in SQL
 Check Clause:

The CHECK clause can also be used in conjunction with the CREATE
DOMAIN statement.

• CREATE DOMAIN D_NUM AS INTEGER


• CHECK (D_NUM > 0 AND D_NUM < 21);
Specifying Constraints in SQL
 Specifying Key and Referential Integrity Constraints:

 PRIMARY KEY clause does not allow duplicate values and null values.
There can be only one primary key in a table.
Create table dept (Dnumber INT PRIMARY KEY);
Here in the table dept, Dnumber column is the primary key and in this
column there should be no duplicate and also null values.

UNIQUE clause can also be specified directly for a unique key if it is a


single attribute.
Create table dept(Mgr_ssn CHAR(9) UNIQUE);
Here the column dname is defined as unique key meaning this column will be
having only unique values but this columns allows null values.
Specifying Constraints in SQL
Specifying Constraints in SQL
 Specifying Key and Referential Integrity Constraints:

Referential Integrity – This means the values of the primary key column of
a table should match with the foreign key column of same table or another
table.

The default action that SQL takes for an integrity violation is to reject the
update operation that will cause a violation, which is known as the
RESTRICT option.
• parent row refers to the row of the table which is containing primary key
• child row refers to the row of the table which is containing foreign key.

• Set NULL : Sets the column value to NULL when you delete or update the
parent table’s row.

• CASCADE : CASCADE will propagate the change when the parent changes. If
you delete or update a row, rows in constrained tables that reference that
row will also be deleted or updated.

• RESTRICT OR NO ACTION : RESTRICT causes you can not delete/update a


given parent row if a child row exists that references the value for that parent
row.

• SET DEFAULT : SET DEFAULT option causes you to set the default value in the
child table column when the parent table row is deleted/updated.
i) Create a table with primary key by giving a name for primary key:

• CREATE TABLE DEPARTMENT


• ( Dnumber int,
• CONSTRAINT DEPTPK PRIMARY KEY(Dnumber),
• Dept_name VARCHAR(25) NOT NULL );
Specifying Constraints in SQL

ii) Create a table with primary key and foreign key by specifying names
for both foreign keys with on delete set null and on update cascade
• CREATE TABLE EMPLOYEE (
• Emp_no int,
• Dno INT DEFAULT 1,
• SSN varchar(9) primary key,
• Super_ssn varchar(9),
• CONSTRAINT EMPSUPERFK FOREIGN KEY (Super_ssn) REFERENCES
EMPLOYEE(Ssn) ON DELETE SET NULL,
• CONSTRAINT EMPDEPTFK FOREIGN KEY(Dno) REFERENCES
DEPARTMENT(Dnumber)ON DELETE SET NULL ON UPDATE CASCADE);
Specifying Constraints in SQL

iii) Create a table with on delete set default:

CREATE TABLE EMPLOYEE


( Emp_no int, Dno INT,
SSN varchar(9) primary key,
CONSTRAINT EMPDEPTFK FOREIGN KEY(Dno) REFERENCES
DEPARTMENT(Dnumber)ON DELETE SET DEFAULT);
Specifying Constraints in SQL

• iv) Create a table with on delete restrict:

• CREATE TABLE EMPLOYEE1 (


• Emp_no int,
• Dno INT DEFAULT 1,
• SSN varchar(9) primary key,
• Super_ssn varchar(9),
• CONSTRAINT EMPDEPTFK FOREIGN KEY(Dno) REFERENCES
DEPARTMENT1(Dnumber) ON DELETE RESTRICT );
Specifying Constraints in SQL

Giving Names to Constraints


 A constraint may be given a constraint name, following the keyword
CONSTRAINT.
The names of all constraints within a particular schema must be
unique. A constraint name is used to identify a particular constraint in
case the constraint must be dropped later.

Specifying Constraints on rows(tuples) Using CHECK


 The table constraints can be specified through additional CHECK
clauses at the end of a CREATE TABLE statement. These can be called
row-based constraints because they apply to each row individually and
are checked whenever a row is inserted or modified.
Specifying Constraints in SQL

 Specifying Constraints on rows(tuples) Using CHECK

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18));
Basic Retrieval Queries in SQL

 SQL has one basic statement for retrieving information from a database:
The SELECT statement
The SELECT-FROM-WHERE Structure of Basic SQL Queries

In SQL, the basic logical comparison operators for comparing attribute values
with one another and with literal constants are =, <=, >, >=, and <>.
Basic Retrieval Queries in SQL

• Select can be used to join two tables using a common column between
the two tables:

SELECT * FROM
employee2, department2
WHERE Dnumber = Dno and Dname = 'Research’;

The condition Dnumber = Dno is called a join condition, because it combines two
tuples(two records or rows): one from DEPARTMENT and one from EMPLOYEE
Example 1 : Retrieve all the information of all employees who work for the
‘Research’ department.

Example 2: Retrieve the name and address of all employees who work for the
‘Research’ department

SELECT fname, lname, address


FROM employee2,department2
WHERE DEPARTMENT2.Dnumber = EMPLOYEE2.Dno and Dname = 'Research’;
Basic Retrieval Queries in SQL

• Example 3 : Creating a table with joined result

• create table emp_dept as


• SELECT fname, lname, address
• FROM employee2,department2
• WHERE
DEPARTMENT2.Dnumber = EMPLOYEE2.Dno and
Dname = 'Research';
Basic Retrieval Queries in SQL

• Ambiguous Attribute Names, Aliasing, Renaming, and Tuple


Variables:
• Example 1: In SQL, the same name can be used for two (or more) attributes
as long as the attributes are in different tables. If this is the case, and a multi
table query refers to two or more attributes with the same name, we must
qualify the attribute name with the relation name to prevent ambiguity.
Example 1:
SELECT fname, lname, address, project_no
FROM employee2,department2,project
WHERE DEPARTMENT2.Dnumber = EMPLOYEE2.Dno and
project.Dnumber = department2.Dnumber and Dname = 'Research’;
Here Ambiguity is prevented by using tables name along with the
column names
Basic Retrieval Queries in SQL

• Example 2:
• select employee2.fname,employee2.lname,project.project_no
• from employee2,department2,project
• WHERE DEPARTMENT2.Dnumber = EMPLOYEE2.Dno and
• project.Dnumber = department2.Dnumber and Dname = 'Research’;
• Here also the ambiguity is prevented by specifying the table names with the
columns.
Basic Retrieval Queries in SQL

• We can use this alias-naming or renaming mechanism in any SQL


query to specify tuple variables for every table in the WHERE
clause.

SELECT *FROM employee2 as e, department2 as d


WHERE d.Dnumber = e.Dno
and Dname = 'Research’;
Basic Retrieval Queries in SQL

• Unspecified WHERE Clause and Use of the Asterisk:


• We discuss two more features of SQL here.
• A missing WHERE clause indicates no condition on row selection;
hence, all rows of the table specified in the FROM clause qualify
and are selected for the query result.
• select * from
• employee2,department2;
Basic Retrieval Queries in SQL

 We use the keyword DISTINCT in the SELECT clause, meaning that only
distinct tuples should remain in the result.
Example 1: select distinct Dno from employee;
Example 2: SELECT DISTINCT Dno FROM DEPARTMENT2, EMPLOYEE2;
Example 3: ( SELECT DISTINCT Dno
FROM DEPARTMENT2, EMPLOYEE2
WHERE employee2.Dno = department2.Dnumber AND employee2.lname =
'Guptha’ )
UNION
(SELECT DISTINCT Dnumber
FROM employee2, project
WHERE employee2.Dno = project.Dnumber AND employee2.lname =
'Guptha' );
Basic Retrieval Queries in SQL

• Substring Pattern Matching and Arithmetic Operators:


 This feature allows comparison conditions on only parts of a character string,
using the LIKE comparison operator. This can be used for string pattern
matching.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Address LIKE ‘%Houston,TX%’;
To retrieve all employees who were born during the 1970s, we can use Query
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Bdate LIKE ‘_ _ 7 _ _ _ _ _ _ _’;
Basic Retrieval Queries in SQL

 Retrieve all employees in department 5 whose salary is between $30,000 and


$40,000.
• SELECT * FROM EMPLOYEE
• WHERE (Salary BETWEEN 30000 AND 40000) AND Dno = 5;
 Ordering of Query Results Ordering of Query Results
SELECT *FROM
employee2, department2
where employee2.Dno = department2.Dnumber
order by employee2.fname;
Basic Retrieval Queries in SQL

• Ascending Order:
• SELECT *FROM employee2, department2
• where employee2.Dno = department2.Dnumber
• order by employee2.fname ASC;
• Descending Order:
• SELECT *FROM employee2, department2
• where employee2.Dno = department2.Dnumber
• order by employee2.fname DESC;
Basic Retrieval Queries in SQL

• Discussion and Summary of Basic SQL Retrieval Queries:


• A simple retrieval query in SQL can consist of up to four clauses, but only the
first two—SELECT and FROM—are mandatory. The clauses are specified in the
following order, with the clauses between square brackets [ … ] being optional.
INSERT, DELETE, and UPDATE
Statements in SQL
 The INSERT Command:
QUERY 1 : INSERT INTO EMPLOYEE (Fname, Lname, Dno, Ssn) VALUES (‘Richard’, ‘Marini’, 4,
‘653298653’);
QUERY 2 : INSERT INTO EMPLOYEE (Fname, Lname, Ssn, Dno) VALUES (‘Robert’, ‘Hatcher’,
‘980760540’, 2);

(Query 2 is rejected if referential integrity checking is provided by DBMS.)

 The DELETE Command: The DELETE command removes tuples(rows) from a relation(table). It
includes a WHERE clause, similar to that used in an SQL query, to select the tuples to be
deleted.

DELETE FROM EMPLOYEE WHERE Lname = ‘Brown’;

DELETE FROM EMPLOYEE WHERE Ssn = ‘123456789’;

DELETE FROM EMPLOYEE WHERE Dno = 5;

DELETE FROM EMPLOYEE;


INSERT, DELETE, and UPDATE
Statements in SQL

The UPDATE Command : The UPDATE command is used to


modify attribute values of one or more selected tuples.
UPDATE PROJECT
SET Plocation = ‘Bellaire’, Dnum = 5
WHERE Pnumber = 10;
Aggregate Functions In SQL

 Aggregate functions are used to summarize information from multiple


rows or records into a single-row summary. Grouping is used to create
subgroups of tuples before summarization.
Grouping and aggregation are required in many database applications, and
we will introduce their use in SQL through examples. A number of built-in
aggregate functions exist: COUNT, SUM, MAX, MIN, and AVG.
The COUNT function returns the number of tuples or values as specified in
a query. The functions SUM, MAX, MIN, and AVG can be applied to a set or
multiset of numeric values. The functions MAX and MIN can also be used
with attributes that have nonnumeric domains.
The syntax for calculating the minimum, maximum and average salaries
i) SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary) FROM
EMPLOYEE
ii) SELECT COUNT (*) FROM EMPLOYEE;
Aggregate Functions In SQL

• ii) SELECT SUM(Salary) AS Total_Sal, MAX(Salary) AS Highest_Sal,


• MIN(Salary) AS Lowest_Sal, AVG(Salary) AS Average_Sal
• FROM EMPLOYEE;

• iv) SELECT SUM(Salary), MAX(Salary), MIN(Salary), AVG(Salary)


• FROM EMPLOYEE
• JOIN DEPARTMENT ON Dno = Dnumber
• WHERE Dname = ‘Research’;

• v) SELECT COUNT(DISTINCT Salary)FROM EMPLOYEE;


Aggregate Functions In SQL

• vi) Query to get the average salary and count of employees from each
department
• SELECT Dno, COUNT(*) as Emp_in_each_dept, AVG (Salary) as
avg_salary
• FROM EMPLOYEE
• GROUP BY Dno;

• vii) Query to get the Nth highest salary from the table (This query can
be used to find 1st highest, 2nd highest , 3rd highest and so on…)
• select * from
• (select * , dense_rank() over (order by salary desc) as
DenseRank from Employee)
• employee
• where DenseRank = 4;
Subqueries:
• Subqueries: A subquery is a SQL query nested inside a larger
query. It can be used in a SELECT, INSERT, UPDATE, or DELETE
statement
• Subqueries used with the select:
• SELECT emp_name
• FROM EMPLOYEE
WHERE (SELECT COUNT(*) FROM DEPENDENT
WHERE Ssn = Essn ) >= 2;
Here Essn is called the employee Ssn which is stored in the dependents table
and Employee table has the SSN Value.
Subqueries used with the insert:
insert into customers1(Customername, city, Country)
(select Suppliername, city, country from suppliers where country =
'germany');
Subqueries:

• Subqueries used with the delete:


• delete from employee
• where Ssn <> all(select Essn from dependent)
Subqueries used with Update:
update employee
set Dno = 1005
where Dno <> all(select Dnumber from department);
Thankyou

You might also like