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

sql-notes

sql-notes

Uploaded by

mosesmainam017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

sql-notes

sql-notes

Uploaded by

mosesmainam017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

lOMoARcPSD|48229334

SQL Notes

Assembly Language Programming (KCA University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by mose maish ([email protected])
lOMoARcPSD|48229334

STRUCTURED QUERY LANGUAGE (SQL).


SQL is a database computer language designed for the retrieval and management of data in a relational
database. SQL stands for Structured Query Language.
SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving
data stored in a relational database.
SQL is the standard language for Relational Database System. All the Relational Database Management
Systems (RDMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL as
their standard database language.
Why SQL?
SQL is widely popular because it offers the following advantages −
 Allows users to access data in the relational database management systems.
 Allows users to describe the data.
 Allows users to define the data in a database and manipulate that data.
 Allows to embed within other languages using SQL modules, libraries & pre-compilers.
 Allows users to create and drop databases and tables.
 Allows users to create view, stored procedure, functions in a database.
 Allows users to set permissions on tables, procedures and views.
SQL DATA TYPES
SQL Data Type is an attribute that specifies the type of data of any object. Each column, variable and
expression has a related data type in SQL. You can use these data types while creating your tables. You can
choose a data type for a table column based on your requirement.
SQL data types can be broadly divided into following categories.
1) Numeric data types such as int, tinyint, bigint, float, real etc.
2) Date and Time data types such as Date, Time, Datetime etc.
3) Character and String data types such as char, varchar, text etc.
4) Binary data types such as binary, varbinary etc.
SQL COMMANDS
The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT,
UPDATE, DELETE and DROP. These commands can be classified into the following groups based on their
nature.
DDL - DATA DEFINITION LANGUAGE
A data definition language (DDL) is a computer language used to create and modify the structure of database
objects in a database. These database objects include views, schemas, tables, indexes, etc.
The commands include
1) Create
2) Alter
3) Drop

Downloaded by mose maish ([email protected])


lOMoARcPSD|48229334

CREATE TABLE COMMAND


This command builds a new table and has a predefined syntax.
The CREATE statement syntax is:
CREATE TABLE [table name]
([column definitions]) [table parameters];

For example:
CREATE TABLE Employee
(Employee Id INTEGER PRIMARY KEY not null,
First name VARCHAR (50),
Last name VARCHAR (75);
The mandatory semi-colon at the end of the statement is used to process every command before it. In this
example, the string CHAR is used to specify the data type.

ALTER TABLE COMMAND


An alter command modifies an existing database table. This command can add up additional column, drop
existing columns and even change the data type of columns involved in a database table.
An alter command syntax is:
ALTER object type object name parameters;
For example:
ALTER TABLE Employee ADD PRIMARY KEY (employee_pk);
In this example, we added a unique primary key to the table to add a constraint and enforce a unique value.
The constraint “employee_pk” is a primary key and is on the Employee table.

DROP TABLE COMMAND


A drop command is used to delete objects such as a table, index or view. A DROP statement cannot be rolled
back, so once an object is destroyed, there’s no way to recover it.
Drop statement syntax is:
DROP object type object name;
For example:
DROP TABLE Employee;
In this example, we’re deleting the Employee table.

Downloaded by mose maish ([email protected])


lOMoARcPSD|48229334

DML - DATA MANIPULATION LANGUAGE


The commands include
1) Select
2) Insert
3) Update
4) Delete

SELECT command
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
WHERE Condition;

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
WHERE Condition;

Example:
SELECT StudentID, StudentFName, Age
FROM Student
WHERE StudentFName=’John’;

INSERT command
The INSERT query command in SQL provides a way to add new rows of information or data inside a
specific database of the RDBMS. INSERT can be executed using two syntaxes:
Syntax:
INSERT INTO TABLE_NAME (column1, column2, column3,…columnN)
VALUES (value1, value2, value3,…valueN);
Here ‘column’ represents the table column’s specific names for inserting data in the desired way.
You may avoid the column name and add the values as defined in the column previously.
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,…valueN);
Example:
Here is an example of adding three records in the customer database table:

Downloaded by mose maish ([email protected])


lOMoARcPSD|48229334

INSERT INTO CUSTOMERS (ID,NAME,AGE,CITY,COMPENSATION)VALUES (1, Kritesh, 45, ‘Delhi’,


2500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,CITY,COMPENSATION)VALUES (2, Mehta, 35,Kochi,
1500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,CITY,COMPENSATION)VALUES (3, Preet, 32, Delhi,
7000.00 );

And using the second syntax, you can add the record as that too:
INSERT INTO CUSTOMERSVALUES (6, ‘Shubhra’, 45, ‘MP’, 4500.00 );

UPDATE Command
The UPDATE command in SQL is used to modify or change the existing records in a table. If we want to
update a particular value, then we use the WHERE clause along with the UPDATE clause.
Syntax
UPDATE table_name
SET col1=val1, col2=val2…
[Where condition];
Where
 UPDATE, SET, and WHERE are the keywords
 table_name is the name of the table you want update
 col1, col2, … are the columns considered to be updated
 val1, val2, … assign new values
 the condition section is where the condition is given, followed by a semicolon.

DELETE Command
The DELETE statement is used to delete existing records in a table.
DELETE Syntax
DELETE FROM table_name
WHERE condition;

Example
The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers" table.
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste';

Downloaded by mose maish ([email protected])


lOMoARcPSD|48229334

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. The syntax is
DELETE FROM table_name;
Example
The following SQL statement deletes all rows in the "Customers" table, without deleting the table:
DELETE FROM Customers;

THE SQL AGGREGATE FUNCTIONS


COUNT FUNCTION
The COUNT() function returns the number of rows that matches a specified criterion.
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;

AVERAGE FUNCTION
The AVG() function returns the average value of a numeric column.
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;

SUM FUNCTION
The SUM() function returns the total sum of a numeric column.
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;

MIN() and MAX() FUNCTIONS

Downloaded by mose maish ([email protected])


lOMoARcPSD|48229334

The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.

MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
EXAMPLES
Below is a selection from the "Products" table in the Northwind sample atabase:

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 bags 18

2 Chang 1 1 24 - 12 oz bottles 19

3 Aniseed Syrup 1 2 12 - 550 ml bottles 10

4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22

5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35

Count Example
The following SQL statement finds the number of products
SELECT COUNT(ProductID)AS ProductCount
FROM Products;

Average Example

The following SQL statement finds the average price of all products:

SELECT AVG(Price)
FROM Products;
6

Downloaded by mose maish ([email protected])


lOMoARcPSD|48229334

MIN() Example
The following SQL statement finds the price of the cheapest product:
SELECT MIN(Price) AS SmallestPrice
FROM Products;

MAX() Example

The following SQL statement finds the price of the most expensive product:

SELECT MAX(Price) AS LargestPrice


FROM Products;

SUM Example
Below is a selection from the "Order Details" table in the Northwind sample database:

OrderDetailID OrderID ProductID Quantity

1 10248 11 12

2 10248 42 10

3 10248 72 5

4 10249 14 9

5 10249 51 40

The following SQL statement finds the sum of the "Quantity" fields in the "Order Details" table

SELECT SUM(Quantity)
FROM OrderDetails;

Downloaded by mose maish ([email protected])


lOMoARcPSD|48229334

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;

Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden


snabbköp Berglund 8

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;

SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column between them.
8

Downloaded by mose maish ([email protected])


lOMoARcPSD|48229334

Different types of the JOINs in SQL include:


1. (INNER) JOIN
Returns records that have matching values in both tables
2. LEFT (OUTER) JOIN
Returns all records from the left table, and the matched records from the right table
3. RIGHT (OUTER) JOIN
Returns all records from the right table, and the matched records from the left table
4. FULL (OUTER) JOIN
Returns all records when there is a match in either left or right table

ORDERS TABLE

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

CUSTOMERS TABLE

CustomerID CustomerName ContactName Country

1 Alfreds Futterkiste Maria Anders Germany

2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico

3 Antonio Moreno Taquería Antonio Moreno Mexico

Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers"
table. The relationship between the two tables above is the "CustomerID" column.
Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records that
have matching values in both tables:
Example
SELECT Orders.OrderID, CustomerName, OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
9

Downloaded by mose maish ([email protected])


lOMoARcPSD|48229334

Resulting table

OrderID CustomerName OrderDate

10308 Ana Trujillo Emparedados y helados 9/18/1996

10365 Antonio Moreno Taquería 11/27/1996

10383 Around the Horn 12/16/1996

10355 Around the Horn 11/15/1996

10278 Berglunds snabbköp 8/12/1996

SQL ALTER TABLE STATEMENT


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;
Example
The following SQL adds an "Email" column to the "Customers" table:
ALTER TABLE Customers
ADD Email varchar(255);
ALTER TABLE - DROP COLUMN
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;
The following SQL deletes the "Email" column from the "Customers" table:
Example
ALTER TABLE Customers
DROP COLUMN Email;

10

Downloaded by mose maish ([email protected])

You might also like