sql-notes (2)
sql-notes (2)
SQL syntax, the set of rules for how SQL statements are written and formatted, is similar to other
programming languages. Some components of SQL syntax include the following:
o Structure query language is not case sensitive. Generally, keywords of SQL are written in
uppercase.
o Statements of SQL are dependent on text lines. We can use a single SQL statement on one or
multiple text line.
o SQL statements start with a SQL command and end with a semicolon (;)
2. String
This kind of data type stores alphanumeric data.
1. Char(n): This data type holds the character string of fixed length, specified by the user. If
the string length is less than the specified length, then the remaining spaces are filled with
blanks which leads to wastage of storage. Well, if you don’t specify the length SQLs DDL
assumes the length of one character. The character data type has a storage space of 254
characters.
2. varchar(n): This data type holds the character string of variable length. It will just store the
exact number of characters that the user specifies thereby saving the storage space. The
varchar has a maximum length of 32,672 characters.
3. Date and Time
This data type holds the data in the context of date and time.
1. date: This data type holds the date in terms of the year, month & day in a particular order
YYYY- MM-DD. Here, the year is expressed in four digits ranging from 0001 to 9999. Whereas,
the month and day are expressed in two digits.
2. time: This data type holds time and expresses it in the format (HH:MM:SS).
3. timestamp: This data type expresses date and time in the format YYYY-MM-DD HH:MM:SS.
It ranges from 1970-01-01 00:00:01 to 9999-12-31 23:59:59.
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 groups based on their nature:
Command Description
SELECT Retrieves certain records from one or more tables
DCL - Data Control Language:
o These SQL commands are used for providing security to database objects.
o The different DCL commands are:
Command Description
GRANT Gives a privilege to user
REVOKE Takes back privileges granted from user
CREATE TABLE
o The SQL CREATE TABLE statement is used to create a new table.
o Creating a basic table involves naming the table and defining its columns and each column's
datatype.
Syntax: Basic syntax of CREATE TABLE statement is as follows:
CREATE TABLE Table_name
(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
o Here CREATE TABLE is the keyword followed by the Table_name, followed by an open
parenthesis, followed by the column names and data types for that column, and followed by aclosed
parenthesis.
o For each column, a name and a data type must be specified and the column name must be aunique
within the table definition.
o Column definitions are separated by commas (,).
o Uppercase and lowercase letters makes no difference in column names.
o Each table must have at least one column.
o SQL commands should end with a semicolon (;).
Example: Create a table “STUDENT” that contains five columns: RegNo, Name, Combination,DOB
and Fees.
CREATE TABLE STUDENT(
RegNo NUMBER (6),
Name VARCHAR2 (15),
Combination CHAR (4),DOB DATE,
Fees NUMBER (9, 2),PRIMARY KEY ( RegNo )
);
It creates an empty STUDENT table which looks like this:
RegNo Name Combination DOB Fees
Viewing the table information:
ALTER Statement:
The table can be modified or changed by using the ALTER command.
Syntax: Basic syntax of ALTER TABLE statement is as follows:
1. ALTER TABLE Table_name
ADD (column_name1 DataType, Cloumn_name2 DataType……);
2. ALTER TABLE Table_name
MODIFY (column_name1 DataType, Cloumn_name2 DataType……);
3. ALTER TABLE Table_name
DROP (column_name1 DataType, Cloumn_name2 DataType……);
Example:
Using the ALTER TABLE command the following tasks cannot be performed
o Changing a table name.
o Changing the column name.
o Decreasing the size of a column if table data exists.
o Changing a column‟s data type.
DROP TABLE:
The SQL DROP TABLE statement is used to remove a table definition and all data, indexes,
triggers, constraints, and permission specifications for that table.
Syntax: Basic syntax of DROP TABLE statement is as follows:
DROP TABLE Table_name;
Example:
INSERT:
The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Here, column1, column2,...columnN are the names of the columns in the table into which you
want to insert data.
You may not need to specify the column(s) name in the SQL query if you are adding values for all the
columns of the table. But make sure the order of the values is in the same order as the columns in
the table.
METHOD 1: The SQL INSERT INTO syntax would be as follows:
UPDATE Table_name
SET column_name = value
[, column_name =value..............]
[WHERE condition];
Example:
SQL> UPDATE STUDENT SET COMBINATION='CEBA' WHERE REGNO=1411;
1 row updated.
SQL> UPDATE STUDENT SET NAME='AKASH' WHERE REGNO=1412;
1 row updated.
DELETE command:
In SQL, an already existing row or rows are removed from tables through the use of DELETE
command.
The basic syntax of DELETE command is given below.
DELETE Table_name
[WHERE condition];
Example:
SQL> DELETE STUDENT WHERE REGNO=1412;
1 row deleted.
SELECT:
SQL SELECT statement is used to fetch the data from a database table which returns data in theform
of result table. These result tables are called result-sets.
[WHERE condition(s)]
[GROUPBY column-list] Optional
[HAVING condition(s)] Part
[ORDER BY column-name(s)];
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;
Following is an example, which would fetch REGNO, NAME and COMBINATION fields of the
customers available in STUDENT table:
DISTINCT:
The SQL DISTINCT keyword is used in conjunction with SELECT statement to eliminate all
the duplicate records and fetching only unique records.
There may be a situation when you have multiple duplicate records in a table. While fetching
such records, it makes more sense to fetch only unique records instead of fetching duplicate
records.
Syntax: The basic syntax of DISTINCT keyword to eliminate duplicate records is as follows:
First, let us see how the following SELECT query returns duplicate combination records:
Now, let us use DISTINCT keyword with the above SELECT query and see the result:
This would produce the following result where we do not have any duplicate entry:
Following is an example, which would fetch REGNO, NAME and COMBINATION fields fromthe
STUDENT table for a COMBINATION is „PCMC‟.
Here, it is important to note that all the strings should be given inside single quotes ('') where as
numeric values should be given without any quote as in above example:
The SQL AND and OR operators are used to combine multiple conditions to narrow data in anSQL
statement. These two operators are called conjunctive operators.
These operators provide a means to make multiple comparisons with different operators in the
same SQL statement.
You can combine N number of conditions using AND operator. For an action to be taken by the SQL
statement, whether it be a transaction or query, all conditions separated by the AND must be TRUE.
Example: Consider the STUDENT table having the following records:
The OR Operator:
The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
Syntax: The basic syntax of OR operator with WHERE clause is as follows:
You can combine N number of conditions using OR operator. For an action to be taken by the
SQL statement, whether it be a transaction or query, only any ONE of the conditions separated
bythe OR must be TRUE.
Following is an example, which would fetch REGNO, NAME and DOB fields from theSTUDENT table
where fees is less than 1500 OR combination is „PCMC:
SELECT column-list
FROM Table_name
[WHERE condition]
[ORDER column1, column2, .. columnN] [ASC | DESC];
BY
You can use more than one column in the ORDER BY clause. Make sure whatever column you
are using to sort, that column should be in column-list.
Example: Consider the STUDENT table having the following records:
Following is an example, which would sort the result in descending order by NAME:
Function Description
AVG Returns average value of „N‟, ignoring NULL values
COUNT(expr) Returns the number of rows where „expr‟ is not NULL
COUNT(*) Returns the number of rows in the table including duplicates and those
with NULL values
Function Description
Numeric Work with numbers.
Functions Examples: ABS, POWER, ROUND, SQRT
Conversion These functions are used to convert one type of data to another.
Functions Example: TO_NUMBER, TO_CHAR, TO_DATE
COUNT ( ) Function:
This function is used to count the number of values in a column.
COUNT (*) is used to count the number of rows in the table including duplicates and those with
NULL values.
Example 1:
o SELECT COUNT (*) FROM EXAMINATION;
o The above query returns 10.
Example 2:
o SELECT COUNT (RegNo) FROM EXAMINATION WHERE CC = „C3‟ ;
o The above query returns 4.
AVG ( ) Function:
This function is used to find the average of the values in a numeric column.
Example 1:
o SELECT AVG (Cs) FROM EXAMINATION;
o The above query returns 74.7
SUM ( ) Function:
This function is used to find the sum of the values in a numeric column.
Example:
o SELECT SUM (Phy) FROM EXAMINATION;
o The above query returns 729
MAX ( ) Function:
This function is used to find the maximum values in a column.
Example:
o SELECT MAX (Phy) FROM EXAMINATION;
o The above query returns 100
MIN ( ) Function:
This function is used to find the minimum values in a column.
Example:
o SELECT MIN (Phy) FROM EXAMINATION;
o The above query returns 33
SQL CONSTRAINTS:
Constraints are the rules enforced on data columns on table.
These are limiting the type of data that can go into a table.
This ensures the accuracy and reliability of the data into the database.
SQL allows two types of constraints.
o Column level constraints: These constraints are defined along with the column definition when
creating or altering a table structure. These constraints apply only to individual columns.
o Table level constraints: These constraints are defined after all the table columns when creating or
altering a table structure. These constraints apply to groups of one or more columns.
Following are the commonly used constraints available in SQL.
Constraints Description
NOT NULL Ensures that a column cannot have NULL value
UNIQUE Ensures that all values in column are different
PRIMARY KEY Uniquely identified eac row in a database table.
FOREIGN KEY Uniquely identified each rown in any other database table
DEFAULT Provides a default value for a column when none is
specified
CHECK Ensures that all values in a column satisfy certain condition.
Creating VIEWs:
Database Views are created using the CREATE VIEW statement.
Views can be created from a single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege according to the specific
implementation.
Syntax: The basic CREATE VIEW syntax is as follows: