Sei sulla pagina 1di 15

DBMS – SQL

3.1 Introduction to SQL


Ideally, a database language allows you to create database and table structures, perform basic data
management chores (add, delete, and modify), and perform complex queries designed to transform the raw
data into useful information. Moreover, a database language must perform such basic functions with minimal
user effort, and its command structure and syntax must be easy to learn. Finally, it must be portable; that is, it
must conform to some basic standard so a person does not have to relearn the basics when moving from one
RDBMS to another. SQL meets those ideal database language requirements well.

SQL functions fit into two broad categories:

• It is a data definition language (DDL). SQL includes commands to create database objects such as tables,
indexes, and views, as well as commands to define access rights to those database objects. Some common data
definition commands you will learn are listed in the table bellow

SQL DATA DEFINITION COMMANDS

COMMAND OR OPTION DESCRIPTION

CREATE SCHEMA AUTHORIZATION Creates a database schema

CREATE TABLE Creates a new table in the user’s database schema

NOT NULL Ensures that a column will not have null values

UNIQUE Ensures that a column will not have duplicate values

PRIMARY KEY Defines a primary key for a table

FOREIGN KEY Defines a foreign key for a table

DEFAULT Defines a default value for a column (when no value is given)

CHECK Validates data in an attribute

CREATE INDEX Creates an index for a table

CREATE VIEW Creates a dynamic subset of rows and columns from one or more tables

ALTER TABLE Modifies a table’s definition

CREATE TABLE AS Creates a new table based on a query in the user’s database schema

DROP TABLE Permanently deletes a table (and its data)


DROP INDEX Permanently deletes an index

DROP VIEW Permanently deletes a view

• It is a data manipulation language (DML). SQL includes commands to insert, update, delete, and retrieve data
within the database tables. The data manipulation commands you will learn in this chapter are listed in the
table bellow

SQL DATA MANIPULATION COMMANDS

COMMAND OR OPTION DESCRIPTION

INSERT Inserts row(s) into a table

SELECT Selects attributes from rows in one or more tables or views

WHERE Restricts the selection of rows based on a conditional expression

GROUP BY Groups the selected rows based on one or more attributes

HAVING Restricts the selection of grouped rows based on a condition

ORDER BY Orders the selected rows based on one or more attributes

UPDATE Modifies an attribute’s values in one or more table’s rows

DELETE Deletes one or more rows from a table

COMMIT Permanently saves data changes

ROLLBACK Restores data to its original values

Comparison operators

=, <, >, <=, >=, <>, != Used in conditional expressions

Logical operators

AND/OR/NOT Used in conditional expressions

Special operators Used in conditional expressions

BETWEEN Checks whether an attribute value is within a range

IS NULL Checks whether an attribute value is null


SQL DATA MANIPULATION COMMANDS

COMMAND OR OPTION DESCRIPTION

LIKE Checks whether an attribute value matches a given string pattern

IN Checks whether an attribute value matches any value within a value list

EXISTS Checks whether a subquery returns any rows

DISTINCT Limits values to unique values

Aggregate functions Used with SELECT to return mathematical summaries on columns

COUNT Returns the number of rows with non-null values for a given column

MIN Returns the minimum attribute value found in a given column

MAX Returns the maximum attribute value found in a given column

SUM Returns the sum of all values for a given column

AVG Returns the average of all values for a given column

SQL is relatively easy to learn. Its basic command set has a vocabulary of fewer than 100 words. Better yet, SQL
is a nonprocedural language: you merely command what is to be done; you do not have to worry about how.
For example, a single command creates the complex table structures required to store and manipulate data
successfully; end-users and programmers do not need to know the physical data storage format or the
complex activities that take place when a SQL command is executed.

There are several different SQL “languages,” their differences are minor. Whether you use Oracle, Microsoft
SQL Server, MySQL, IBM’s DB2, Microsoft Access, or any other well-established RDBMS, a software manual
should be sufficient to get you up to speed.

At the heart of SQL is the query. Actually, in the SQL environment, the word query covers both questions and
actions. Most SQL queries are used to answer questions such as these: “What products currently held in
inventory are priced over $100, and what is the quantity on hand for each of those products?” or “How many
employees have been hired since January 1, 2016, by each of the company’s departments?” However,
many SQL queries are used to perform actions such as adding or deleting table rows or changing attribute
values within tables. Still other SQL queries create new tables or indexes. In short, for a DBMS, a query is simply
a SQL statement that must be executed. However, before you can use SQL to query a database, you must
define the database environment for SQL with its data definition commands.

3-2 The Database Model


The Database Model

A simple database composed of the following tables is used to illustrate the SQL commands
in this chapter: CUSTOMER, INVOICE, LINE, PRODUCT, and VENDOR. This database model is shown in Figure
The database model in the above Figure reflects the following business rules:

 A customer may generate many invoices. Each invoice is generated by one customer.

 An invoice contains one or more invoice lines. Each invoice line is associated with one invoice.

 Each invoice line references one product. A product may be found in many invoice lines. (You can sell
more than one hammer to more than one customer.)

 A vendor may supply many products. Some vendors do not yet supply products. For example, a vendor
list may include potential vendors.

 If a product is vendor-supplied, it is supplied by only a single vendor.

 Some products are not supplied by a vendor. For example, some products may be produced in-house
or bought on the open market.

The database model contains many tables. However, to illustrate the initial set of data definition commands,
the focus of attention will be the PRODUCT and VENDOR tables.

The above ERD (ER Diagram) shows

 The VENDOR table contains vendors who are not referenced in the PRODUCT table. Database
designers note that possibility by saying that "PRODUCT" is optional to "VENDOR"; a vendor may exist
without a reference to a product.

 Existing V_CODE values in the PRODUCT table must (and do) have a match in the VENDOR table to
ensure referential integrity.

 A few products are supplied factory-direct, a few are made in-house, and a few may have been bought
in a warehouse sale. In other words, a product is not necessarily supplied by a vendor. Therefore,
"VENDOR" is optional to PRODUCT.
Table name: VENDOR

Table name: PRODUCT

SQL Datatypes

In the data dictionary in Table 7.3, note the data types selected. Keep in mind that datatype selection is usually
dictated by nature and the intended use of the data. For example:

P_PRICE clearly requires some kind of numeric data type

vendor name is an obvious candidate for a character data type

V_AREACODE because it contains only digits.

P_INDATE to be a DATE field rather than a character field


SOME COMMON SQL DATA TYPES

Numeric Date and Time String

INT DATE CHAR

BIGINT DATETIME VARCHAR

BOOLEAN TIME TEXT

FLOAT YEAR ENUM

DOUBLE TIMESTAMP

REAL

BIT

However, because this chapter is designed to introduce the basics of SQL, the discussion is limited to the data
types summarized in Table above.

3.3 SQL Data Definition Commands


Data Definition Language (DDL)
SQL commands are used for creating, modifying, and dropping the structure of database objects.

The commands are

 CREATE,
 ALTER,
 DROP,
 RENAME, and
 TRUNCATE

These commands are used to create, alter, and drop tables, views, and indexes, and they are covered first in this
chapter. There may be other objects controlled by the DDL, depending on the DBMS. For example, many DBMSs
support defining synonyms (abbreviations) for database objects or a field to hold a specified sequence of numbers
(which can be helpful in assigning primary keys to rows in tables). In a production database, the ability to use DDL
commands will generally be restricted to one or more database administrators in order to protect the database
structure from unexpected and unapproved changes. In development or student databases, DDL privileges will be
granted to more users.

For SQL – Hands on Practices –p,ease use the following website:


https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

Use an Updated web browsers to run SQL Commands.

SQL - Crate Database

Create a new database


CREATE DATABASE DatabaseName;

Example
CREATE DATABASE kwikstop;

After creating the Database we need to use it.

USE DatabaseName;

Example
USE kwikstop;

These commands will run only in the Database Management server. Do not try it.

SQL ─ CREATE Table

Creating a basic table involves naming the table and defining its columns and each
column's data type.
The SQL CREATE TABLE statement is used to create a new table.

Syntax
The basic syntax of the CREATE TABLE statement is as follows:

CREATE TABLE table_name(


column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);

CREATE TABLE is the keyword telling the database system what you want to do. In this case, you want to create
a new table. The unique name or identifier for the table follows the CREATE TABLE statement.
Then in brackets comes the list defining each column in the table and what sort of data type it is. The syntax
becomes clearer with the following example.

Example

The following code block is an example, which creates a CUSTOMERS table with an ID as a primary key and
NOT NULL are the constraints showing that these fields cannot be NULL while creating records in this table:

CREATE TABLE Customer(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

SQL - ALTER TABLE

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype

To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a
column):

ALTER TABLE table_name


DROP COLUMN column_name

SQL ─ DROP or DELETE Table

The SQL DROP TABLE statement is used to remove a table definition and all the data, indexes, triggers,
constraints and permission specifications for that table.

NOTE: You should be very careful while using this command because once a table is deleted then all the
information available in that table will also be lost forever.

Syntax

The basic syntax of this DROP TABLE statement is as follows:

DROP TABLE table_name;

Example:

DROP TABLE Customer;


3.4 SQL - Data Manipulation Commands
The Data Manipulation Language (DML) is the subset of SQL used to add, update and delete data.

The Data Manipulation Commands are:

 SELECT,
 INSERT,
 UPDATE, and
 DELETE

3.4.1 SQL ─ INSERT Query


The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.

Syntax
There are two basic syntaxes of the INSERT INTO statement which are shown below.

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)] VALUES (value1, value2, value3,...valueN);

INSERT INTO TABLE_NAME VALUES (value1, value2, value3,...valueN);

Examples:

INSERT INTO CUSTOMER (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMER (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMER (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMER (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMER (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

You can create a record in the CUSTOMERS table by using the second syntax as shown below.

INSERT INTO CUSTOMERS


VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );

3.4.2 SQL ─ SELECT Query


The SQL SELECT statement is used to fetch the data from a database table that returns this data in the form of a
result table. These result tables are called result-sets.

Select Query has different Clause

SELECT, FROM, WHERE, LIKE, TOP, LIMIT, ROWNUM, ORDER BY, SORTING and Group By and has different keywords
like Distinct, and *

SQL - Select Clause

Syntax

The basic syntax of the SELECT statement is as follows.:

SELECT column1, column2, columnN FROM table_name;

Here, column1, column2... are the fields of a table whose values you want to fetch. If you want to fetch all the fields
available in the field, then you can use the following syntax.

SELECT * FROM table_name;


Example:

SELECT * FROM Customers;

The above command will display all the columns from the table Customers

SELECT CustomerID, CustomerName, City, Country FROM Customers;

This above command will display only the four columns mentioned in the SELECT clause.

SQL ─ WHERE Clause

The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with
multiple tables. If the given condition is satisfied, then only returns specific value from the table. You should use the
WHERE clause to filter the records and fetching only the necessary records. The WHERE clause is not only used in the
SELECT statement, but it is also used in the update, DELETE statement, etc., which we would examine in the
subsequent chapters.

Syntax

The basic syntax of the SELECT statement with the WHERE clause is as shown below.

SELECT column1, column2, columnN


FROM table_name
WHERE [condition]

You can specify a condition using the comparison or logical operators like >, <, =, LIKE, NOT, etc. The following
examples would make this concept clear.

Example:

SELECT ProductName, Unit, Price FROM Products WHERE Price BETWEEN 20 AND 30

SELECT * FROM [Suppliers] WHERE City ='Tokyo'

The first command display ProductName, Unit, Price columns where Price BETWEEN 20 AND 30

The Second command display all columns where City ='Tokyo'

SQL ─ LIKE Clause

The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards
used in conjunction with the LIKE operator.

 The percent sign (%)


 The underscore (_)

The percent sign represents zero, one or multiple characters. The underscore represents
a single number or character. These symbols can be used in combinations.

Syntax
The basic syntax of % and _ is as follows:

58
The SQL LIKE clause is used to compare a value to similar values using wildcard
operators. There are two wildcards used in conjunction with the LIKE operator.
The percent sign (%)
The underscore (_)
The percent sign represents zero, one or multiple characters. The underscore represents
a single number or character. These symbols can be used in combinations.
Syntax
The basic syntax of % and _ is as follows:

SELECT FROM table_name


WHERE column LIKE 'XXXX%'

or

SELECT FROM table_name


WHERE column LIKE '%XXXX%'

or

SELECT FROM table_name


WHERE column LIKE 'XXXX_'
or

SELECT FROM table_name


WHERE column LIKE '_XXXX'

or

SELECT FROM table_name


WHERE column LIKE '_XXXX_'

You can combine N number of conditions using AND or OR operators. Here, XXXX could be any numeric or string
value.

For the better understanding do the following commands

CREATE TABLE CUST_DET(


ID INT NOT NULL auto_increment,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

INSERT INTO CUST_DET VALUES('1','Ramesh', '32','Ahmedabad', '2000.00');

INSERT INTO CUST_DET VALUES('2','Kumar', '25','Delhi', '1500');

INSERT INTO CUST_DET VALUES('3','kaushik', '23','Kolkota', '2000');

INSERT INTO CUST_DET VALUES('4','Chaitali', '25','Mumbai', '6500');

INSERT INTO CUST_DET VALUES('5','Rajaram', '28','Chennai', '8000');

Display the Data from CUST_DET

SELECT * FROM CUST_DET;

Now look the following commands:

SELECT * FROM CUST_DET WHERE SALARY LIKE '200%';

SELECT * FROM CUST_DET WHERE SALARY LIKE '_00%';

SELECT * FROM CUST_DET WHERE SALARY LIKE '_5__';

The above command will display list of CUST_DET where

1. salary 200% the starting value is 200 and it may contain any characteristers
2. salary contains first one letter and it contains two 0 (Zero) and after that any letters.
3. salary contains first number, than 5, then two numbers.

LIMIT Clause

MySQL supports the LIMIT clause to fetch a limited number of records.

Syntax

The basic syntax of the TOP clause with a SELECT statement would be as follows.

SELECT * FROM table_name


WHERE [condition]

LIMIT 2

Example:

SELECT * FROM CUST_DET LIMIT 3

ORDER BY Clause

The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns.
Some databases sort the query results in an ascending order by default.

Syntax
The basic syntax of the ORDER BY clause is as follows:
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

ORDER BY will display the table in sending or descending order

SELECT * FROM CUST_DET ORDER BY AGE ASC

SQL ─ Group By

The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange
identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT
statement and precedes the ORDER BY clause.

Syntax

The basic syntax of a GROUP BY clause is shown in the following code block. The GROUP BY clause must follow the
conditions in the WHERE clause and must precede the ORDER BY clause if one is used.

SELECT column1, column2


FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1 ASC, column2 DESC

Example

SELECT AGE, COUNT(SALARY) FROM CUST_DET GROUP BY AGE;

3.4.3 SQL ─ Conjunctive Operators


An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to perform the
operation(s), such as comparisons and arithmetic operations. These Operators are used to specify conditions in an
SQL statement and to serve as conjunctions for multiple conditions in a statement.

 Arithmetic operators
 Comparison operators
 Logical operators
 Operators used to negate conditions

Use the link to work on examples:


https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all
copy and paste the example in this SQL Statement: box and click Run SQL.

SQL Arithmetic Operators

Operator Description Hands-on

+ Addition - Adds values on either side of the operator. SELECT 10+


20 AS Result;

- Subtraction - Subtracts right-hand operand from the SELECT 10 *


left-hand operand. 20 AS Result;

* Multiplication - Multiplies values on either side of the SELECT 10 *


operator. 20 AS Result;

/ Division - Divides left-hand operand by right-hand SELECT 10 /


operand. 20 AS Result;

If you run the above statements, SQL will perform the intended operations and store the answer in the name of the
Result.
SQL Comparison Operators

Operator Description Hands-on

= Checks if the values of two SELECT * FROM Products WHERE CategoryID=3;


operands are equal or not,
if yes then condition
becomes true.

!= or Checks if the values of two SELECT * FROM Orders WHERE ShipperID<>3;


<> operands are equal or not,
if values are not equal then
the condition becomes true.

> Checks if the value of the SELECT * FROM Products WHERE Price>30;
left operand is greater than
the value of right operand,
if yes then condition
becomes true.

< Checks if the value of the SELECT * FROM Products WHERE Price<30;
left operand is less than the
value of right operand, if
yes then condition becomes
true.

>= Checks if the value of the SELECT * FROM Products WHERE Price>=30;
left operand is greater than
or equal to the value of
right operand, if yes then
condition becomes true.

<= Checks if the value of the SELECT * FROM Products WHERE Price<=30;
left operand is less than or
equal to the value of right
operand, if yes then
condition becomes true.

If you run these above statements in SQL, it compares the WHERE clause. If it is true it displays the data from the
database.

Logical Operators

Operat Descripti Hands-on


or on

AND The AND SELECT * FROM Products WHERE CategoryID=3 AND Price<=30;
operator
allows
the
existenc
e of
multiple
conditio
ns in an
SQL
stateme
nt's
WHERE
clause.

OR The OR SELECT * FROM Categories WHERE CategoryName='Beverages' OR


operator CategoryName='Dairy Products';
is used
to
combine
multiple
conditio
ns in an
SQL
stateme
nt's
WHERE
clause.

LIKE The LIKE SELECT * FROM Employees WHERE Notes LIKE '% BA %';
operator
is used
to
compare
a value
to
similar
values
using
wildcard
operator
s.

NOT The NOT SELECT * FROM Categories WHERE CategoryName NOT LIKE 'Bevera
operator ges';
reverses
the
meaning
of the
logical
operator
with
which it
is used.

BETWE The SELECT * FROM OrderDetails WHERE Quantity BETWEEN 12 AND 20


EN BETWEE ;
N
operator
is used
to
search
for
values
that are
within a
set of
values,
given
the
minimu
m value
and the
maximu
m value.

If you run these above statements in SQL, it compares the WHERE clause. If it is true it displays the data from the
database.

3.4.4 SQL ─ UPDATE Query


The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE clause with the
UPDATE query to update the selected rows, otherwise all the rows would be affected.

Syntax

The basic syntax of the UPDATE query with a WHERE clause is as follows:

UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

You can combine N number of conditions using the AND or the OR operators.

Example:

UPDATE Customers SET CustomerName='Rajarajan' WHERE CustomerID = 1

The above command will change CustomerName to Rajarajan where CustomerID = 1

The updated list will be displayed by the command

SELECT * FROM Customers

3.4.5 SQL ─ DELETE Query


The SQL DELETE Query is used to delete the existing records from a table.
You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be
deleted.

Syntax

The basic syntax of the DELETE query with the WHERE clause is as follows:

DELETE FROM table_name


WHERE [condition];

You can combine N number of conditions using AND or OR operators.

DELETE FROM CUSTOMERS WHERE CustomerID = 1;

The updated data table is shown by

SELECT * FROM CUSTOMERS;

Potrebbero piacerti anche