Essential SQL Features and Commands
Essential SQL Features and Commands
SQL allows us to interact with the database and bring out/ manipulate
data within them. Using SQL, we can create our own databases and
then add data into these databases in the form of tables.
The following functionalities can be performed on a database using
SQL:
o Create or delete a database
o Create of alter or delete some tables in a database
o Select data from tables
o Insert data into tables
o Update data in tables
o Delete data from tables
o Create views in the database
o Execute various aggregate functions.
2. Tables
All data in the database are organized efficiently in the form of tables.
A database can be formed a collection of multiple tables, where each
table would be linked with each other by using some relations.
Example:
ID Name Phone Class
INTEGER VARCHAR(25) VARCHAR(12) INTEGER
The above example is for a table of students and stores their Name,
Phone and Class as data. The ID is assigned to each student and using
this ID, we can relate data from this table to other tables.
SQL-Create Table:
SQL-Delete Table:
o To delete a table from a database, we use the DROP command.
DROP TABLE student;
To allow the users to work with tables effectively, SQL provides us with
various data types each of which can be useful based on the type of
data we handle.
String Datatypes:
The table below lists all the Sytring type datatypes available in
SQL, along with their descriptions:
Datatype Description
Date/Time Datatypes:
The data types available in SQL to handle Date/Time operations
effectively are called the Date/Time data types. The below table lists all the
Date/Time variables in SQL along with their description:
Datatype Description
DATE Stores date in YYYY-MM-DD format
with dates in range of ‘1000-01-01’
to ‘9999-12-31’.
TIME(fsp) Stores time in hh:mm:ss format with
times in range of ‘-839:59:59’ to
‘839:59:59’.
DATETIME(fsp) Stores a combination of date and
time in YYYY-MM-DD and hh:mm:ss
format, with values in the range of
‘1000-01-01 00:00:00’ to ‘9999-12-
31 23:59:59’
TIMESTAMP(fsp) It stores values relative to the unix
epoch, basically a unix timestamp.
Values lie in the range of ‘1970-01-
01 00:00:01’ UTC to ‘2038-01-09’
03:14:07’ UTC.
YEAR Stores values of years as a 4 digit
number format, with a range lying
between -1901 to 2155.
4. SQL Commands
SQL commands are instructions that are used by the user to
communicate with the database, to perform specific tasks, functions
and queries of data.
UPDATE Student
SET User_Name = “DeepPatel”
WHERE Student_Id = 2;
In the above example, the query deletes the row where the
Name of the student is “Scalar” from the Student Table.
SAVEPOINT SAVED;
DELETE FROM STUDENTS
WHERE AGE = 16;
ROLLBACK TO SAVED;
5. SQL Constraints
Constraints are rules which are applied on a table. For example,
specifying valid limits or ranges on data in the table etc.
The valid constraints in SQL are:
NOT NULL: Specifies that this column cannot store a NULL value.
The above example will insert into the student table having
the values 1, Scaler, +1234-5678 and 12 to the columns ID,
name, phone and class columns.
8. Clauses in SQL
Clauses are in-built functions available in SQL and are used for filtering
and analyzing data quickly allowing the user to efficiently extract the
required information from the database.
The below table lists some of the important SQL clauses and their
description with examples:
Name Description Example
WHERE Used to select data SELECT * from
from the database Employee WHERE
based on some age >= 18;
conditions.
AND Used to combine 2 or SELECT * from
more conditions and Employee WHERE
returns true if all the age >= 18 AND
conditions are True salary >= 45000 ;
OR Similar to AND but Select * from
returns true if any of Employee where
the conditions are salary >= 45000 OR
True. age >= 18;
LIKE Used to search for a SELECT * FROM
specified pattern in a Students WHERE
column. Name LIKE ‘a%’;
LIMIT Puts a restriction on SELECT * FROM
how many rows are table1 LIMIT 3;
returned from a query.
ORDER BY Used to sort given SELECT * FROM
data in Ascending or student ORDER BY
Descending order. age ASC;
GROUP BY Groups rows that have SELECT
the same values into COUNT(StudentID),
summary rows. State FROM
Students GROUP
BY State;
9. SQL Operators
Operators are used in SQL to form complex expressions which can be
evaluated to code more intricate queries and extract more precise data from
a database.
There are 3 main types of operators: Arithmetic, Comparision and
Logical operators, each of which will be described below.
o Arithmetic Operators:
Arithmetic Operators allows the user to perform arithmetic
operations in SQL. The table below shows the list of arithmetic
operators available in SQL:
Operators Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
Bitwise Operators: Bitwise operators are used to performing Bit
manipulation operations in SQL. The table below shows the list of
bitwise operators available in SQL:
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
Operator Description
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
Compound Operators: Compound operators are basically a
combination of 2 or more arithmetic or relational operator, which
can be used as a shorthand while writing code. The table below
shows the list of compound operators available in SQL:
Operator Description
+= Add equals
-= Subtract equals
*= Multiply equals
/= Divide equals
%= Modulo equals
&= AND equals
|= OR equals
^= XOR equals
Operator Description
ALL Returns true if all subqueries meet the given
condition.
AND Returns true if all the conditions turn out to be
true.
ANY True if any of the subqueries meet the given
condition
BETWEEN True if the operand lies within the range of the
conditions
EXISTS True if the subquery returns one or more
records
IN Returns True if the operands to at least one of
the operands in a given list of expressions
LIKE Return True if the operand and some given
pattern match.
NOT Displays some record if the set of given
conditions is False
OR Returns True if any of the conditions turn out
to be True
SOME Returns True if any of the Subqueries meet the
given condition.
Types of Keys:
1. Primary Key: They uniquely identify a row in a table.
Properties:
o Only a single primary key for a table. (A special case is a
composite key, which can be formed by the composition of 2 or
more columns, and act as a single candidate key.)
o The primary key column cannot have any NULL values.
o The primary key must be unique for each row.
Example:
CREATE TABLE Student (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Class int,
PRIMARY KEY (ID)
);
The above example creates a table called STUDENT with some given
properties(columns) and assigns the ID column as the primary key of the
table. Using the value of ID column, we can uniquely identify its
corresponding row.
2. Foreign Key: Foreign keys are keys that reference the primary keys
of some other table. They establish a relationship between 2 tables and link
them up.
Example: In the below example, a table called Orders is created with
some given attributes and its Primary Key is declared to be OrderID and
Foreign Key is declared to be PersonId referenced from the Person's table. A
person's table is assumed to be created beforehand.
Amongst these, the Primary and Foreign keys are most commonly
used.
Name Description
ABS Returns the absolute value of a number.
ASIN Returns arc sine of a number.
AVG Returns average value of an expression.
COUNT Count the number of record returned by
select query.
EXP Returns a raised to the power of a number.
FLOOR Returns the greatest integer<= the number.
RAND Returns the random number
SIGN Returns the sign of a number.
SQRT Returns the square root of a number.
SUM Returns the sum of a set of values
Name Description
CAST Typecast a value into specified
datatype.
CONVERT Converts a value into specified
datatype.
IIF Returns a true if a condition evaluates
to true, else some other value.
ISNULL Returns the specified value if expression
is NULL, else returns the expression.
ISNUMERIC Checks if expression is numeric or not.
SYSTEM_USER Returns the login name for the current
user.
USER_NAME Returns the database user name based
on the specified id.
Example:
Consider the following tables,
Let us try to build the below table, using Joins,
NATURAL JOIN: It is a special type of inner join based on the fact that
the column names and datatypes are the same on both tables.
Syntax:
Select * from table1 Natural JOIN table2;
Example:
Select * from Customers Natural JOIN Orders;
In the above example, we are merging the Customers and Orders table
shown above using a NATURAL JOIN based on the common column
customer_id.
RIGHT JOIN: Returns all of the records from the second table, along
with any matching records from the first.
Example :-
SELECT [Link], [Link], [Link]
FROM Orders
RIGHT JOIN Employees
ON [Link] = [Link]
ORDER BY [Link];
LEFT JOIN: Returns all of the records from the first table, along with any
matching records from the second table.
Example:-
SELECT [Link], [Link]
FROM Customers
LEFT JOIN Orders
ON [Link]=[Link]
ORDER BY [Link];
FULL JOIN: Returns all records from both tables when there is a match.
Example:-
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
FULL JOIN ORDERS
ON [Link] = ORDERS.CUSTOMER_ID;
Example:
CREATE TRIGGER trigger1
before INSERT
ON Student
FOR EACH ROW
SET [Link] = ([Link]/ 10) * 100;
Here, we create a new Trigger called trigger1, just before we perform an
INSERT operation on the Student table, we calculate the percentage of the
marks for each row.
Some common operations that can be performed on triggers are:
DROP: This operation will drop an already existing trigger from the
table.
Syntax:
DROP TRIGGER trigger name;
SHOW: This will display all the triggers that are currently present in
the table.
Syntax:
SHOW TRIGGERS IN database_name;
Example:
CREATE PROCEDURE SelectAllCustomers AS SELECT * FROM
Customers;
GO;
The above example creates a stored procedure called ‘SelectAllCustomers’,
which selects all the records from the customer table.
The above image shows an example of SQL injections, through the use of 2
tables - students and library.