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

SQL

SQL, or Structured Query Language, is a standard language for managing and manipulating databases, supported by various systems like MySQL and Oracle. It enables users to execute queries, retrieve, insert, update, and delete records, as well as create databases and tables. The document also outlines key SQL commands, syntax, and examples for using SQL effectively in database management.

Uploaded by

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

SQL

SQL, or Structured Query Language, is a standard language for managing and manipulating databases, supported by various systems like MySQL and Oracle. It enables users to execute queries, retrieve, insert, update, and delete records, as well as create databases and tables. The document also outlines key SQL commands, syntax, and examples for using SQL effectively in database management.

Uploaded by

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

SQL is a standard language for storing, manipulating and retrieving data

in databases. Our SQL tutorial will teach you how to use SQL in: MySQL,
SQL Server, MS Access, Oracle, Sybase, Informix, Postgres, and other
database systems. SQL is a standard language for accessing and
manipulating databases

What is SQL?

 SQL stands for Structured Query Language

 SQL lets you access and manipulate databases

 SQL became a standard of the American National Standards


Institute (ANSI) in 1986, and of the International Organization for
Standardization (ISO) in 1987

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

SQL is a Standard - BUT....

Although SQL is an ANSI/ISO standard, there are different versions of the


SQL language. However, to be compliant with the ANSI standard, they all
support at least the major commands (such
as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.

Note: Most of the SQL database programs also have their own proprietary
extensions in addition to the SQL standard!

Using SQL in Your Web Site

To build a web site that shows data from a database, you will need:

 An RDBMS database program (i.e. MS Access, SQL Server, MySQL)


 To use a server-side scripting language, like PHP or ASP

 To use SQL to get the data you want

 To use HTML / CSS to style the pa

RDBMS

RDBMS stands for Relational Database Management System. RDBMS is


the basis for SQL, and for all modern database systems such as MS SQL
Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS
is stored in database objects called tables. A table is a collection of related
data entries, and it consists of columns and rows. Look at the "Customers"
table:

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)

 DROP INDEX - deletes an index

---------------------------------------------------------------------

Select all records from the Customers table:

SELECT * FROM Customers;

--------------------------------------------------------------------

The SQL SELECT Statement

The SELECT statement is used to select data from a database.

Syntax

SELECT column1, column2, ...


FROM table_name;
Example Return data from the Customers table:

SELECT CustomerName, City FROM Customers;

The SQL SELECT DISTINCT Statement

The SELECT DISTINCT statement is used to return only distinct (different)


values.

Example Select all the different countries from the "Customers" table:

SELECT DISTINCT Country FROM Customers;

Count Distinct

By using the DISTINCT keyword in a function called COUNT, we can return


the number of different countries.

Example

SELECT COUNT(DISTINCT Country) FROM Customers;

Here is a workaround for MS Access:

Example

SELECT Count(*) AS DistinctCountries


FROM (SELECT DISTINCT Country FROM Customers);

The SQL WHERE Clause

The WHERE clause is used to filter records. It is used to extract only those
records that fulfill a specified condition.

Example Select all customers from Mexico:

SELECT * FROM Customers


WHERE Country='Mexico';

Text Fields vs. Numeric Fields

SQL requires single quotes around text values (most database systems
will also allow double quotes). However, numeric fields should not be
enclosed in quotes:

Example

SELECT * FROM Customers


WHERE CustomerID=1;

Operators in The WHERE Clause

You can use other operators than the = operator to filter the search.
Example Select all customers with a CustomerID greater than 80:

SELECT * FROM Customers


WHERE CustomerID > 80;

The following operators can be used in the WHERE clause:

Operator Description

= Equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

<> Not equal. Note: In some versions of SQL this


operator may be written as !=

BETWEEN Between a certain range

LIKE Search for a pattern

IN To specify multiple possible values for a column

SELECT * FROM Products WHERE Price BETWEEN 50 AND 60;

SELECT * FROM Customers WHERE City LIKE 's%';

SELECT * FROM Customers WHERE City IN ('Paris','London');

The SQL ORDER BY

The ORDER BY keyword is used to sort the result-set in ascending or


descending order.

Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

DESC

The ORDER BY keyword sorts the records in ascending order by default. To


sort the records in descending order, use the DESC keyword.

Example Sort the products from highest to lowest price:

SELECT * FROM Products


ORDER BY Price DESC;

Order Alphabetically

For string values the ORDER BY keyword will order alphabetically:

Example Sort the products alphabetically by ProductName:

SELECT * FROM Products


ORDER BY ProductName;

Alphabetically DESC

To sort the table reverse alphabetically, use the DESC keyword:

Example Sort the products by ProductName in reverse order:

SELECT * FROM Products


ORDER BY ProductName DESC;

ORDER BY Several Columns

The following SQL statement selects all customers from the "Customers"
table, sorted by the "Country" and the "CustomerName" column. This
means that it orders by Country, but if some rows have the same Country,
it orders them by CustomerName:

Example

1. SELECT * FROM Customers ORDER BY Country,


CustomerName;
2. SELECT * FROM Customers ORDER BY Country ASC,
CustomerName DESC;

The SQL AND Operator

The WHERE clause can contain one or many AND operators.


The AND operator is used to filter records based on more than one
condition, like if you want to return all customers from Spain that starts
with the letter 'G':
Syntax

SELECT column1, column2, ...


FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;

The SQL OR Operator

The WHERE clause can contain one or more OR operators.


The OR operator is used to filter records based on more than one
condition, like if you want to return all customers from Germany but also
those from Spain

Syntax

SELECT column1, column2, ...


FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;

All Conditions Must Be True

The following SQL statement selects all fields


from Customers where Country is "Germany" AND City is "Berlin"
AND PostalCode is higher than 12000:

Example

SELECT * FROM Customers


WHERE Country = 'Germany'
AND City = 'Berlin'
AND PostalCode > 12000;

Combining AND and OR

You can combine the AND and OR operators. The following SQL statement
selects all customers from Spain that starts with a "G" or an "R". Make
sure you use parenthesis to get the correct result.

Example Select all Spanish customers that starts with either "G" or "R":

SELECT * FROM Customers


WHERE Country = 'Spain' AND (CustomerName LIKE 'G
%' OR CustomerName LIKE 'R%');

At Least One Condition Must Be True

The following SQL statement selects all fields from Customers where
either City is "Berlin", CustomerName starts with the letter "G"
or Country is "Norway":

Example
SELECT * FROM Customers
WHERE City = 'Berlin' OR CustomerName LIKE 'G%' OR Country
= 'Norway';

The NOT Operator

The NOT operator is used in combination with other operators to give the
opposite result, also called the negative result.

Syntax

SELECT column1, column2, ...


FROM table_name
WHERE NOT condition;

NOT LIKE

Example Select customers that does not start with the letter 'A':

SELECT * FROM Customers


WHERE CustomerName NOT LIKE 'A%';

NOT BETWEEN

Example Select customers with a customerID not between 10 and 60:

SELECT * FROM Customers


WHERE CustomerID NOT BETWEEN 10 AND 60;

NOT IN

Example Select customers that are not from Paris or London:

SELECT * FROM Customers


WHERE City NOT IN ('Paris', 'London');

NOT Greater Than

Example Select customers with a CustomerId not greater than 50:

SELECT * FROM Customers


WHERE NOT CustomerID > 50;

Note: There is a not-greater-than operator: !> that would give you the
same result.

NOT Less Than

Example Select customers with a CustomerID not less than 50:

SELECT * FROM Customers


WHERE NOT CustomerId < 50;
Note: There is a not-less-than operator: !< that would give you the same
result.

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:

1. Specify both the column names and the values to be inserted:

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


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

2. 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.
Here, the INSERT INTO syntax would be as follows:

INSERT INTO table_name


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

INSERT INTO Example The following SQL statement inserts a new record
in the "Customers" table:

INSERT INTO Customers (CustomerName, ContactName, Address, City,


PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');

Insert Data Only in Specified Columns

It is also possible to only insert data in specific columns. The following SQL
statement will insert a new record, but only insert data in the
"CustomerName", "City", and "Country" columns (CustomerID will be
updated automatically):

Example

INSERT INTO Customers (CustomerName, City, Country)


VALUES ('Cardinal', 'Stavanger', 'Norway');

Insert Multiple Rows

It is also possible to insert multiple rows in one statement. To insert


multiple rows of data, we use the same INSERT INTO statement, but with
multiple values:

Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway'),
('Greasy Burger', 'Per Olsen', 'Gateveien 15', 'Sandnes', '4306', 'Norway'),
('Tasty Tee', 'Finn Egan', 'Streetroad 19B', 'Liverpool', 'L1 0AA', 'UK');

Note: Make sure you separate each set of values with a comma ,.

What is a NULL Value?

A field with a NULL value is a field with no value. If a field in a table is


optional, it is possible to insert a new record or update a record without
adding a value to this field. Then, the field will be saved with a NULL
value.

Note: A NULL value is different from a zero value or a field that contains
spaces. A field with a NULL value is one that has been left blank during
record creation!

How to Test for NULL Values?

It is not possible to test for NULL values with comparison operators, such
as =, <, or <>. We will have to use the IS NULL and IS NOT
NULL operators instead.

IS NULL Syntax

SELECT column_names
FROM table_name
WHERE column_name IS NULL;

The IS NULL operator is used to test for empty values (NULL values). The
following SQL lists all customers with a NULL value in the "Address" field:

Example

SELECT CustomerName, ContactName, Address


FROM Customers
WHERE Address IS NULL;

IS NOT NULL Syntax

SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

The IS NOT NULL operator is used to test for non-empty values (NOT NULL
values). The following SQL lists all customers with a value in the "Address"
field:
Example

SELECT CustomerName, ContactName, Address


FROM Customers
WHERE Address IS NOT NULL;

The SQL UPDATE Statement

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;

UPDATE Table

The following SQL statement updates the first customer (CustomerID = 1)


with a new contact person and a new city.

Example

UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

UPDATE Multiple Records

It is the WHERE clause that determines how many records will be updated.

The following SQL statement will update the ContactName to "Juan" for all
records where country is "Mexico":

Example

UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';

The SQL DELETE Statement

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

DELETE Syntax

DELETE FROM table_name WHERE condition;

SQL DELETE Example

The following SQL statement deletes the customer "Alfreds Futterkiste"


from the "Customers" table:
Example

DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

Delete All Records

It is possible to delete all rows in a table without deleting the table. This
means that the table structure, attributes, and indexes will be intact:

DELETE FROM table_name;

The following SQL statement deletes all rows in the "Customers" table,
without deleting the table:

Example

DELETE FROM Customers;

Delete a Table

To delete the table completely, use the DROP TABLE statement:

Example

Remove the Customers table:

DROP TABLE Customers;

SQL TOP, LIMIT, FETCH FIRST or ROWNUM Clause

The SQL SELECT TOP Clause

The SELECT TOP clause is used to specify the number of records to return.
The SELECT TOP clause is useful on large tables with thousands of
records. Returning many records can impact performance.

Example Select only the first 3 records of the Customers table:

SELECT TOP 3 * FROM Customers;

Note: Not all database systems support the SELECT TOP clause. MySQL
supports the LIMIT clause to select a limited number of records, while
Oracle uses FETCH FIRST n ROWS ONLY and ROWNUM.

SQL Server / MS Access Syntax:

SELECT TOP number|percent column_name(s)


FROM table_name
WHERE condition;

MySQL Syntax:

SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;

LIMIT

The following SQL statement shows the equivalent example for MySQL:

Example Select the first 3 records of the Customers table:

SELECT * FROM Customers


LIMIT 3;

FETCH FIRST

The following SQL statement shows the equivalent example for Oracle:

Example Select the first 3 records of the Customers table:

SELECT * FROM Customers


FETCH FIRST 3 ROWS ONLY;

SQL TOP PERCENT Example

The following SQL statement selects the first 50% of the records from the
"Customers" table (for SQL Server/MS Access):

Example SELECT TOP 50 PERCENT * FROM Customers;

The following SQL statement shows the equivalent example for


Oracle:

Example SELECT * FROM Customers FETCH FIRST 50 PERCENT ROWS


ONLY;

ADD a WHERE CLAUSE

The following SQL statement selects the first three records from
the "Customers" table, where the country is "Germany" (for SQL
Server/MS Access):

SELECT TOP 3 * FROM Customers


WHERE Country='Germany';

The following SQL statement shows the equivalent example for


MySQL:

SELECT * FROM Customers


WHERE Country='Germany'
LIMIT 3;

The following SQL statement shows the equivalent example for


Oracle:
SELECT * FROM Customers
WHERE Country='Germany'
FETCH FIRST 3 ROWS ONLY;

ADD the ORDER BY Keyword

Add the ORDER BY keyword when you want to sort the result, and return
the first 3 records of the sorted result.

For SQL Server and MS Access:

Sort the result reverse alphabetically by CustomerName, and


return the first 3 records:

SELECT TOP 3 * FROM Customers


ORDER BY CustomerName DESC;

The following SQL statement shows the equivalent example for


MySQL:

SELECT * FROM Customers


ORDER BY CustomerName DESC
LIMIT 3;

The following SQL statement shows the equivalent example for


Oracle:

SELECT * FROM Customers


ORDER BY CustomerName DESC
FETCH FIRST 3 ROWS ONLY;

SQL Aggregate Functions - An aggregate function is a function that


performs a calculation on a set of values and returns a single value.

Aggregate functions are often used with the GROUP BY clause of


the SELECT statement. The GROUP BY clause splits the result-set into
groups of values and the aggregate function can be used to return a
single value for each group.

The most commonly used SQL aggregate functions are:

 MIN() - returns the smallest value within the selected column

 MAX() - returns the largest value within the selected column

 COUNT() - returns the number of rows in a set

 SUM() - returns the total sum of a numerical column

 AVG() - returns the average value of a numerical column

Aggregate functions ignore null values (except for COUNT()).


The SQL MIN() and MAX() Functions

1. SELECT MIN(Price)
FROM Products;
2. SELECT MAX(Price)
FROM Products;

Set Column Name (Alias) - When you use MIN() or MAX(), the returned
column will not have a descriptive name. To give the column a descriptive
name, use the AS keyword:

1. SELECT MIN(Price) AS SmallestPrice


FROM Products;

Group By:

1. SELECT MIN(Price) AS SmallestPrice, CategoryID


FROM Products
GROUP BY CategoryID;

Count()

1. SELECT COUNT(*)
FROM Products;
2. SELECT COUNT(ProductName)
FROM Products; (Note: If you specify a column name instead of (*),
NULL values will not be counted.)
3. SELECT COUNT(ProductID)
FROM Products
WHERE Price > 20;

Ignore Duplicates You can ignore duplicates by using the DISTINCT


keyword in the COUNT() function. If DISTINCT is specified, rows with the
same value for the specified column will be counted as one.

Example: How many different prices are there in the Products table:

1. SELECT COUNT(DISTINCT Price) FROM Products;

Use Alias: SELECT COUNT(*) AS [Number of records]


FROM Products;

Count() with Group BY: SELECT COUNT(*) AS [Number of records],


CategoryID
FROM Products
GROUP BY CategoryID;

SUM:
1. SELECT SUM(Quantity)
FROM OrderDetails;
2. SELECT SUM(Quantity)
FROM OrderDetails
WHERE ProductId = 11;
3. SELECT SUM(Quantity) AS total
FROM OrderDetails;
4. SELECT OrderID, SUM(Quantity) AS [Total Quantity]
FROM OrderDetails
GROUP BY OrderID;
5. Sum() with an Expression: SELECT SUM(Quantity * 10)
FROM OrderDetails; (If we assume that each product in
the OrderDetails column costs 10 dollars, we can find the total
earnings in dollars by multiply each quantity with 10)
6. SELECT SUM(Price * Quantity)
FROM OrderDetails
LEFT JOIN Products ON OrderDetails.ProductID = Products.ProductID;

Same way you can use AVG() instead of SUM() :


The AVG() function returns the average value of a numeric
column.

SQL LIKE Operator | SQL Wildcard Characters: The LIKE operator is


used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:

 The percent sign % represents zero, one, or multiple characters

 The underscore sign _ represents one, single character

1. SELECT * FROM Customers


WHERE CustomerName LIKE 'a%';
2. SELECT * FROM Customers
WHERE city LIKE 'L_nd__'; (The _ Wildcard) (NOTE: Return all
customers from a city that starts with 'L' followed by one wildcard
character, then 'nd' and then two wildcard characters)
3. SELECT * FROM Customers
WHERE city LIKE '%L%'; (The % Wildcard | Contains)
4. SELECT * FROM Customers
WHERE CustomerName LIKE 'a%' OR CustomerName LIKE 'b%';
5. SELECT * FROM Customers
WHERE CustomerName LIKE 'b%s';
6. SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%'; (Combine Wildcards)
7. SELECT * FROM Customers
WHERE Country LIKE 'Spain'; (Without Wildcard)

You might also like