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

Lecture 6

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

Lecture 6

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Structured Query Language (SQL)

Creating/ Dropping a database


Creating/ Dropping a table
Data types
Adding/ Modifying/ Dropping records
Listing table records
Select subquery

> CHANGE, EVERYDAY


Creating/ Dropping a database
Some of The Most Important SQL Commands:
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
> CHANGE, EVERYDAY
DROP INDEX - deletes an index
Creating a database
The CREATE DATABASE statement is used to create a new
SQL database.
Syntax:
CREATE DATABASE databasename;

Example:
The following SQL statement creates a database called
"testDB":
CREATE DATABASE testDB;

> CHANGE, EVERYDAY


Dropping a database
The DROP DATABASE statement is used to drop an existing
SQL database.
Syntax:
DROP DATABASE databasename;

Example:
The following SQL statement drops the existing database
called "testDB":
DROP DATABASE testDB;
Note: Be careful before dropping a database. Deleting
a database will result in loss of complete information
stored in the database! > CHANGE, EVERYDAY
Creating a table in a database
The CREATE TABLE statement is used to create a new table in a database.
Syntax:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
Example:
The following SQL statement creates a table called "Persons" that contains five
columns: PersonID, LastName, FirstName, Address, and City:
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
); > CHANGE, EVERYDAY
Dropping a table in a database
The DROP TABLE statement is used to drop an existing table
in a database.
Syntax:
DROP TABLE table_name;

Example:
The following SQL statement drops the existing table
"Shippers":
DROP TABLE Shippers;

> CHANGE, EVERYDAY


Data types
Each column in a database table is required to have a name
and a data type.
An SQL developer must decide what type of data that will be
stored inside each column when creating a table. The data
type is a guideline for SQL to understand what type of data is
expected inside of each column, and it also identifies how SQL
will interact with the stored data.

In SQL there are three main data types: string, numeric, and
date and time.

> CHANGE, EVERYDAY


Data types
String data types:
Data type Description Max size Storage
char(n) Fixed width character string 8,000 characters Defined width

varchar(n) Variable width character string 8,000 characters 2 bytes + number of chars

varchar(max) Variable width character string 1,073,741,824 characters 2 bytes + number of chars

text Variable width character string 2GB of text data 4 bytes + number of chars

nchar Fixed width Unicode string 4,000 characters Defined width x 2

nvarchar Variable width Unicode string 4,000 characters

nvarchar(max) Variable width Unicode string 536,870,912 characters

ntext Variable width Unicode string 2GB of text data

binary(n) Fixed width binary string 8,000 bytes

varbinary Variable width binary string 8,000 bytes

varbinary(max) Variable width binary string 2GB

image Variable width binary string 2GB

> CHANGE, EVERYDAY


Numeric data types:
Data type Description Storage

bit Integer that can be 0, 1, or NULL


tinyint Allows whole numbers from 0 to 255 1 byte
smallint Allows whole numbers between -32,768 and 32,767 2 bytes

int Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes

bigint Allows whole numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 8 bytes

decimal(p,s) Fixed precision and scale numbers.Allows numbers from -10^38 +1 to 10^38 –1. 5-17 bytes
The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal
point). p must be a value from 1 to 38. Default is 18.
The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p.
Default value is 0

numeric(p,s) Fixed precision and scale numbers.Allows numbers from -10^38 +1 to 10^38 –1. 5-17 bytes
The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal
point). p must be a value from 1 to 38. Default is 18.
The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p.
Default value is 0

smallmoney Monetary data from -214,748.3648 to 214,748.3647 4 bytes

money Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 bytes

float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308.The n parameter indicates whether the field should hold 4 or 8 4 or 8 bytes
bytes. float(24) holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is 53.

real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes


> CHANGE, EVERYDAY
Date and Time data types:
Data type Description Storage

datetime From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds 8 bytes

datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds 6-8 bytes

smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute 4 bytes

date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes

time Store a time only to an accuracy of 100 nanoseconds 3-5 bytes

datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10 bytes

timestamp Stores a unique number that gets updated every time a row gets created or modified. The timestamp value
is based upon an internal clock and does not correspond to real time. Each table may have only one
timestamp variable

> CHANGE, EVERYDAY


Other data types:

Data type Description

sql_variant Stores up to 8,000 bytes of data of various data types, except text, ntext,
and timestamp

uniqueidentifier Stores a globally unique identifier (GUID)

xml Stores XML formatted data. Maximum 2GB

cursor Stores a reference to a cursor used for database operations

table Stores a result-set for later processing

> CHANGE, EVERYDAY


Adding records
The INSERT INTO statement is used to insert new records in a
table.

INSERT INTO Syntax:


It is possible to write the INSERT INTO statement in two ways.
The first way specifies both the column names and the values
to be inserted:

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

> CHANGE, EVERYDAY


If you are adding values for all the columns of the table, you
do not need to specify the column names in the SQL query.
However, make sure the order of the values is in the same
order as the columns in the table. The INSERT INTO syntax
would be as follows:

INSERT INTO table_name


VALUES (value1, value2, value3, ...);

> CHANGE, EVERYDAY


Modifying records
The UPDATE statement is used to modify the existing
records in a table.
UPDATE Syntax

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

> CHANGE, EVERYDAY


Dropping records
The DELETE statement is used to delete existing records in a
table.
DELETE Syntax

DELETE FROM table_name WHERE condition;

Note: Be careful when deleting records in a table! Notice


the WHERE clause in the DELETE statement. The WHERE
clause specifies which record(s) should be deleted. If you
omit the WHERE clause, all records in the table will be
deleted!

> CHANGE, EVERYDAY


Listing table records
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-
set.
SELECT Syntax
SELECT column1,column2, ...
FROM table_name;

Here, column1, column2, ... are the field names of the table you
want to select data from. If you want to select all the fields
available in the table, use the following syntax:

SELECT * FROM table_name;


> CHANGE, EVERYDAY
Select Subquery
A subquery is a SQL query nested inside a larger query.
A subquery may occur in :
- A SELECT clause
- A FROM clause
- A WHERE clause
The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE
statement or inside another subquery.
A subquery is usually added within the WHERE Clause of another SQL SELECT
statement.
You can use the comparison operators, such as >, <, or =. The comparison
operator can also be a multiple-row operator, such as IN, ANY, or ALL.
A subquery is also called an inner query or inner select, while the statement
containing a subquery is also called an outer query or outer select.
The inner query executes first before its parent query so that the results of an
inner query can be passed to the outer query.
> CHANGE, EVERYDAY
Select Subquery
You can use a subquery in a SELECT, INSERT, DELETE, or UPDATE
statement to perform the following tasks:
Compare an expression to the result of the query.
Determine if an expression is included in the results of the query.
Check whether the query selects any rows.
Syntax:

The subquery (inner query) executes once before the main query (outer
query) executes.
The main query (outer query) use the subquery result.
> CHANGE, EVERYDAY
Select Subquery
SQL Subqueries Example :
We have the following two tables 'student' and 'marks' with
common field 'StudentID'.
student marks

Now we want to write a query to identify all students who get


better marks than that of the student who's StudentID is 'V002',
but we do not know the marks of 'V002'.
> CHANGE, EVERYDAY
To solve the problem, we require two queries. One query
returns the marks (stored in Total_marks field) of 'V002' and a
second query identifies the students who get better marks
than the result of the first query.
First Query:
SELECT * FROM `marks` WHERE studentid = 'V002';

Query results:

The result of the query is 80.

> CHANGE, EVERYDAY


Using the result of this query, here we have written another
query to identify the students who get better marks than 80.
Here is the query:
Second Query:
SELECT a.studentid, a.name, b.total_marks FROM student a,
marks b WHERE a.studentid = b.studentid AND b.total_marks
>80;

Query Results:

Above two queries identified students who get the better


> CHANGE, EVERYDAY
number than the student who's StudentID is 'V002' (Abhay).
You can combine the above two queries by placing one query
inside the other. The subquery (also called the 'inner query') is
the query inside the parentheses. See the following code and
query result :

SELECT a.studentid, a.name, b.total_marks FROM student a,


marks b WHERE a.studentid = b.studentid AND b.total_marks >
(SELECT total_marks FROM marks WHERE studentid = 'V002');

Query Results:

> CHANGE, EVERYDAY

You might also like