0% found this document useful (0 votes)
102 views29 pages

5.3 SQL

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

5.

3 STRUCTURED QUERY
LANGUAGE (SQL)
Prepared by: Mohammad Nabeel Arshad
SQL INTRODUCTION:

 Structured Query language (SQL) pronounced as "S-Q-L" or sometimes


as "See-Quel“ is actually the standard language for dealing with Relational
Databases.
 SQL is a a standard of the American National Standards Institute (ANSI)
 SQL is a programming language that is used to communicate with and
manipulate databases. In order to get the most of the mounds of data they
collect, many businesses must become versed in SQL.
 It is a standardized programming language, deals with relational database
and performs various operations with data such as update, delete, query,
insert. All the RDBMS(Relational Database Management Systems) such as
Oracle, MySQL use SQL as their standard database language.
Further, the SQL language is divided into clauses,
expressions, queries, statements etc.
SQL is a declarative, not an imperative programming
language. It allows users to define and describe the data,
create and drop tables. SQL has many more different
functions.
SQL IS A STANDARD LANGUAGE FOR STORING,
MANIPULATING AND RETRIEVING DATA IN DATABASES.
What Can SQL do?
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views
5.3.1 SQL TO MANIPULATE DATA AND DATA
STRUCTURES
SQL is important because of the following main reasons -
a. SQL helps you to find the needed information or data easily.
b. SQL is a query language, not a programming language. You can easily write
commands almost same as you write English.
c. It quickly stores and gets data from the database quickly. SQL is used for the
query, insert, collect and manages data from the database.
d. Almost every database system will need SQL for further processing.
 SQL is an exceptional reason programming language that is utilized to interface
with databases.
 It works by understanding and analyzing databases that include data fields in their
tables.
 For example, we can take a large organization where a lot of data have to be
stored and managed.
 The organization has to collect and store all the information from the various
departments.
 All the gathered information is organized and stored in a database, but it has to
be valuable and accessible — that’s the place where SQL comes in
5.3.2 SQL COMMANDS, FEATURES, AND
FUNCTIONS TO MANIPULATE DATA

SQL commands are a set of instructions that are used to interact with the database like Sql
Server, MySql, Oracle etc.
SQL commands are responsible to create and to do all the manipulation on the database.
These are also responsible to give/take out access rights on a particular database.

Basic SQL commands are: SELECT, UPDATE, DELETE, INSERT, WHERE


WE HAVE DIFFERENT SQL COMMANDS FOR DIFFERENT-DIFFERENT
PURPOSE. WE CAN GROUPED SQL COMMANDS INTO FIVE MAJOR
CATEGORIES DEPENDING ON THEIR FUNCTIONALITY.

1. Data Definition Language (DDL)


 These SQL commands are used to create, modify, and drop the structure of database objects like table, view, procedure,
indexes etc. In this category we have CREATE, ALTER, DROP and TRUNCATE commands.
2. Data Manipulation Language (DML)
 These SQL commands are used to store, modify, and delete data from database tables. In this category we have INSERT,
UPDATE, and DELETE commands.
3. Data Query Language (DQL)
 These SQL commands are used to fetch/retrieve data from database tables. In this category we have only SEELCT command.
4. Transaction Control Language (TCL)
 These SQL commands are used to handle changes which affect the data in database. Basically we use these commands with
in the transaction or to make a stable point during changes in database at which we can rollback the database state if
required. In this category we have SAVEPOINT, ROLLBACK and COMMIT commands.
5. Data Control Language (DCL)
 These SQL commands are used to implement security on database objects like table, view, stored procedure etc. In this
category we have GRANT and REVOKE commands.
THE MOST IMPORTANT SQL STATEMENTS:

SQL keywords are NOT case sensitive: select is the same as SELECT
 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)
 DROP INDEX - deletes an index
SQL COMMANDS, FEATURES, AND FUNCTIONS
TO MANIPULATE DATA:

We will go through the following sub topics:

a. perform queries and subqueries


b. create tables using appropriate data types
c. populate tables/insert, amend, delete
d. link tables (UNION, JOIN)
e. use wildcards (% and _)
f. grouping, ordering, counting
CREATE TABLES USING APPROPRIATE DATA TYPES

 The SQL CREATE TABLE Statement


 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,
....
);
 The column parameters specify the names of the columns of the table.
 The datatype parameter specifies the type of data the column can hold (e.g. varchar,
integer, date, etc.).
 CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
POPULATE TABLES/INSERT, AMEND, DELETE

 The SQL INSERT INTO Statement


 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, ...);
 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
INSERT INTO Customers
(Customer Name, Address, City, Postal Code, Country)

VALUES
('Hekkan Burger', 'Gateveien 15', 'Sandnes', '4306', 'Norway');

Customer Name Address City Postal Code Country


Hekkan Burger Gateveien 15 Sandnes 4306 Norway
AMEND TABLE

 The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.
 The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.

 ALTER TABLE - ADD Column


 To add a column in a table, use the following syntax:
 ALTER TABLE table_name
ADD column_name datatype;
 The following SQL adds an "Email" column to the "Customers" table:
 Example
 ALTER TABLE Customers
ADD Email varchar(255);
The UPDATE statement is used to change a column value for one or more database table rows.
The UPDATE statement is typically in three parts:
 The tableName to update
 The SET clause which specifies the columns to update
 The WHERE clause, which specifies which rows to include in the update operation.

BEGIN TRANSACTION
UPDATE HumanResources.Department
SET Name = 'Information Technology'
WHERE DepartmentID =

SELECT DepartmentID, Name, GroupName


FROM HumanResources.Department
ROLLBACK
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.

 DROP TABLE table_name;

 DROP TABLE Shippers;


DELETE RECORD

The DELETE statement is used to delete rows from a table. If you want to remove a
specific row from a table you should use WHERE condition.
 DELETE FROM table_name [WHERE condition];
 But if you do not specify the WHERE condition it will remove all the rows from the
table.
 DELETE FROM table_name;
Example:
Problem: Delete products over $50.
DELETE Product
WHERE UnitPrice > 50

Results: 7 records deleted.


When you use the drop statement it deletes the table's row together with the
table's definition so all the relationships of that table with other tables will no
longer be valid.
When you drop a table:
 Table structure will be dropped
 Relationship will be dropped
 Integrity constraints will be dropped
 Access privileges will also be dropped
LINK TABLES (UNION, JOIN)

The SQL UNION Operator


 The UNION operator is used to combine the result-set of two or more SELECT statements.
 Each SELECT statement within UNION must have the same number of columns
 The columns must also have similar data types
 The columns in each SELECT statement must also be in the same order

 The following SQL statement returns the cities (only distinct values) from both the "Customers" and the
"Suppliers" table:
 Example

JOIN TABLES

 Joins allow you to link data from two or more tables together into a single query result--
from one single SELECT statement.

 A "Join" can be recognized in a SQL SELECT statement if it has more than one table after
the FROM keyword.
 This particular "Join" is known as an "Inner Join" or "Equijoin". This is the most common
type of "Join" that you will see or use.

select order_date, order_amount


 from customers
 join orders
 on customers.customer_id = orders.customer_id
 where customer_id = 3
USE WILDCARDS (% AND _)

 A wildcard character can be used to substitute for any other character(s) in a


string.
 SQL wildcards are used to search for data within a table.

Two wildcard characters:


 the percent sign (%) and the underscore (_), are the most common

% A substitute for zero or more characters


_ A substitute for a single character
THE FOLLOWING TABLE HAS A NUMBER OF EXAMPLES SHOWING THE
WHERE PART HAVING DIFFERENT LIKE CLAUSES WITH '%' AND '_'
OPERATORS.



 


GROUPING, ORDERING, COUNTING

 The GROUP BY Statement in SQL is used to arrange identical data into groups
with the help of some functions. i.e if a particular column has same values in
different rows then it will arrange these rows in a group.
 Important Points:
 GROUP BY clause is used with the SELECT statement.
 In the query, GROUP BY clause is placed after the WHERE clause.
 In the query, GROUP BY clause is placed before ORDER BY clause if used any.
SELECT COUNT (CustomerID), Country
FROM Customers
GROUP BY Country;
ORDERING

 The ORDER BY statement in sql is used to sort the fetched data in


either ascending or descending according to one or more columns.
 By default ORDER BY sorts the data in ascending order.
 We can use the keyword DESC to sort the data in descending order and
the keyword ASC to sort in ascending order.
 Syntax of all ways of using ORDER BY is shown below:
 Sort according to one column: To sort in ascending or descending order
we can use the keywords ASC or DESC respectively.
 Syntax:
 SELECT * FROM table_name ORDER BY column_name ASC|DESC
 SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
COUNTING

 The SQL COUNT() function returns the number of rows in a table satisfying the
criteria specified in the WHERE clause. It sets the number of rows or non NULL
column values.
COUNT() returns 0 if there were no matching rows
 Syntax:
 The following statement counts the number of products
 SELECT COUNT(ProductID)
FROM Products;
PERFORM QUERIES AND SUBQUERIES

A query is an operation that retrieves data from one or more tables or views. In this
reference, a top-level SELECT statement is called a query, and a query nested
within another SQL statement is called a subquery.

A subquery is a SQL query within a query.


 Subqueries are nested queries that provide data to the enclosing query.
 Subqueries can return individual values or a list of records
 Subqueries must be enclosed with parenthesis

You might also like