TM07 Using Basic Structured Query Language
TM07 Using Basic Structured Query Language
Lap Test
Task 1: Connect your SQL server
Task 2: Create a new quer
Unit Two: Data definition language
2.1. Introduction to SQL data definition language commands
The Data Definition Language (DDL) is part of SQL that you use to create (completely define) a database,
modify its structure, and destroy it when you no longer need it.
It contains SQL commands you use to create, change, or destroy the basic elements of a relational
database. Basic elements include tables, views, schemas, catalogs, clusters, indexes, stored procedures,
functions and possibly other things as well. Schema is an overall structure that includes tables within it.
Tables and schemas are two elements of a relational database‘s containment hierarchy. You can break
down the containment hierarchy as follows:
Tables contain columns and rows.
Schemas contain tables and views.
Catalogs contain schemas.
2.2. Database planning
Identify all tables.
Define the columns that each table must contain.
Give each table a primary key that you can guarantee is unique.
Make sure that every table in the database has at least one column in common with one other table
in the database. These shared columns serve as logical links that enable you to relate information
in one table to the corresponding information in another table.
Put each table in third normal form (3NF) or better to ensure the prevention of insertion, deletion,
and update anomalies.
2.1. Usage of relevant naming convention for all database elements
Table Name
Column Name
Data Types
There is a standard that specifies various types of data that can be stored in SQL-based
database and manipulated by the SQL languages.
Character strings:
Data type Description Storage
char(n) or Fixed-lengthcharacterstring.Maximum8,000characters N
character(n)
varchar(n) Variable-lengthcharacterstring.Maximum8,000characters
varchar(max) Variable-lengthcharacterstring.Maximum1,073,741,824
characters
Text Variable-lengthcharacterstring.Maximum2GBoftextdata
Unicode strings:
Data type Description Storage
nchar(n) Fixed-lengthUnicodedata.Maximum4,000characters
nvarchar(n) Variable-lengthUnicodedata.Maximum4,000characters
nvarchar(max) Variable-lengthUnicodedata.Maximum536,870,912characters
Ntext Variable-lengthUnicodedata.Maximum2GBoftextdata
Binary types:
Data type Description Storage
binary(n) Fixed-lengthbinarydata.Maximum8,000bytes
varbinary(n) Variable-lengthbinarydata.Maximum8,000bytes
varbinary(max) Variable-lengthbinarydata.Maximum2GB
Image Variable-lengthbinarydata.Maximum2GB
Number types:
Data type Description Storage
timestamp Stores a unique number that gets updated every time a row gets created
or modified.Thetimestampvalueisbaseduponaninternalclockanddoesnot
correspond to real time. Each table may have only one timestamp
variable
Other data types:
Datatype Description
uniqueidentifier Storesagloballyuniqueidentifier(GUID)
Table Storesaresult-setforlaterprocessing
Fixed-length character strings: columns holding these types of data typically store names of
people and companies, addresses, descriptions, and so on.
Integers: columns holding this types of data typically store counts, quantities, ages, and so on.
Integer‘s columns are also frequently used to contain Id numbers, such as customers, employee.
And order numbers.
Decimal numbers: columns with this type store numbers that have fractional parts and must
becalculated exactly, suchas rates and percentages.Theyarealso frequentlyused to store money
amounts.
Extended data Types
Variable-lengthCharacterstring: SQLwhichsupportsVARCHATdata.Whichallowsa
column to store character strings that vary in length from row to row, up to some maximum
length.
Datesandtimes:supportsfordate/timevalues.
Booleandata:supportslogical(TRUEorFALSE)valuesasanexplicittype.
Data Types Differences
Thedifferencesb/nthedatatypesofferedinvariousSQLimplementationisoneofthepractical barriers
to the portability of SQL based applications.
Example:Date/timedataprovidesanexcellentexampleofthesesdifferences.
Date:w/cstoresadatelikeJune30,2009or30June2009
Constants In some SQL statements a numeric, character, or date data value must be expressed in text
form. For example: INSERT statement, w/c adds a student to the database:
The value for each column in the newly inserted row is specified in the VALUES clause.
Constant data values are also used in expression such as in the SELECT statement
SELECT
city
FROMoffice
Numeric constant
Integers and decimal constants (also called exact numeric literals) are written as ordinary decimal
numbers in SQL statements, with an optional leading plus or minus sign
Example:200 +345.95 -500 789.00
Use a comma between the digits of a numeric constant
String Constant
TheANSI/ISOstandardspecifiesthatSQLconstantsforcharacterdatabeenclosedinsingle quotes
(‘……’)
Example:‗WaksumMotuma‘ ‗Addis Ababa‘
Ifasinglequotesistobeusedincludedintheconstanttext,itis writtenwithintheconstantastwo
consecutive single quote characters. This isconstant value:
Example:―Ican‘t‖
Date and time constants
InSQLproductsthesupportsdate/timedata.Constantvaluesfordates,times,andtimeintervalsare
specified as string constants.The format of these constants varies from one DBMS to the next.
Example:
SELECTName,dept
FROMstudent
WHEREhire-date=To-date(‗June30,2009‘,‗monDDyyyy‘)
Expressions
ExpressionsareusedintheSQLLanguagestocalculatevaluesthatareretrievedfromthedatabaseand
to calculate values used in searching the database.
Example1:Thequerythatcalculatesthe sales ofeachoffices asapercentageofitstarget:
SELECTcity,target,sales,(sales/target)*100
FROMoffices
Example2:
SELECT city
FROMoffices
WHEREsales>target+50000.00
Relationships
If one table in a database contains as a foreign key a column that is a primary key in another table in the
database, you can add a constraint to the first table so that it references the second table.
Example:
CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT
NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );
CREATE TABLE ORDERS (ID INT NOT NULL, O_DATE DATETIME, CUSTOMER_ID INT foreign
key references CUSTOMERS(ID),AMOUNT Decimal(8,2), PRIMARY KEY (ID));
For defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
CREATE TABLE CUSTOMERS(ID INT NOT NULL,NAME VARCHAR (20) NOT NULL,AGE INT
NOT NULL, ADDRESS CHAR (25),SALARY DECIMAL (18, 2), PRIMARY KEY (ID, NAME));
CHECK Constraint:
The CHECK Constraint enables a condition to check the value being entered into a record. If the
condition evaluates to false, the record violates the constraint and isn‘t entered into the table.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here,
we add a CHECK with AGE column, so that you cannot have any CUSTOMER below 18 years:
CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL CHECK (AGE >= 18), ADDRESS CHAR (25) ,SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));
SQL NOT NULL Constraint
By default, a table column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This means that
you cannot insert a new record, or update a record without adding a value to this field.
The following SQL enforces the "P_Id" column and the "LastName" column to not
CREATETABLEPersons
(P_IdintNOTNULL,
LastNamevarchar(255)NOTNULL, FirstName
varchar(255),
Addressvarchar(255),
City varchar(255))
CREATETABLEPersons (P_IdintNOTNULLUNIQUE,
Addressvarchar(255),
City varchar(255))
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns,
use the following SQL syntax:
CREATETABLEPersons (P_IdintNOTNULL,
CONSTRAINTuc_PersonIDUNIQUE(P_Id,LastName))
SQL DEFAULT Constraint
The DEFAULT constraint is used to insert a default value into a column.
The default value will be added to all new records, if no other value is specified.
The following SQL creates a DEFAULT constraint on the "City" column when the ―Persons"
table is created:
Create table persons(P_IdintNOTNULL,LastNamevarchar(255)
NOTNULL, FirstName
varchar(255),Addressvarchar(255),
Cityvarchar(255)DEFAULT'Sandnes')
The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():
Create table orders (oid int not null, ono int not null)
SQL AUTO INCREMENT Field
Auto-increment allows a unique number to be generated when a new record is inserted in to a table.
AUTO INCREMENT a Field
Very often we would like the value of the primary key field to be created automatically every
time a new record is inserted.
We would like to create an auto-increment field in a table.
SyntaxforSQLServer
ThefollowingSQLstatementdefinesthe"P_Id"columntobeanauto-incrementprimarykey field in
the "Persons" table:
CREATETABLEPersons (
P_IdintPRIMARYKEYIDENTITY,
LastNamevarchar(255)NOTNULL, FirstName
varchar(255),
Addressvarchar(255),
City varchar(255))
TheMSSQLServerusestheIDENTITYkeywordtoperformanauto-incrementfeature.
Bydefault,thestartingvaluefor IDENTITYis1,anditwillincrementby1foreachnew record.
Tospecifythatthe"P_Id"columnshouldstartat value10andincrementby5,changethe identity to
IDENTITY(10,5).
Toinsertanewrecordintothe"Persons"table,wewillnothavetospecifyavalueforthe "P_Id" column (a
unique value will be added automatically):
INSERTINTOPersons(FirstName,LastName) VALUES
('Lars','Monsen')
The SQL statement above would insert a new record into the "Persons" table. The "P_Id"
columnwouldbeassignedauniquevalue.The"FirstName"columnwouldbesetto"Lars"and the
"LastName" column would be set to "Monsen".
ALTER
After you create a table, you‘re not necessarily stuck with that exact table forever. As you use the table,
you may discover that it‘s not everything you need it to be. You can use the ALTER TABLE command to
change the table by adding, changing, or deleting a column in the table. In addition to tables, you can also
ALTER columns and domains.To create a PRIMARY KEY constraint on the "ID" column when
CUSTOMERS table above already exists, use the following SQL syntax:
ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID);
NOTE: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must
already have been declared to not contain NULL values (when the table was first created).
If ORDERS table has already been created, and the foreign key has not yet been set, use the syntax for
specifying a foreign key by altering a table. ALTER TABLE ORDERS ADD FOREIGN KEY
(Customer_ID) REFERENCES CUSTOMERS (ID);
To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when CUSTOMERS table
already exists, use the following SQL syntax:
ALTER TABLE CUSTOMERS ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME);
If ORDERS table has already been created, and the foreign key has not yet been set, use the syntax for
specifying a foreign key by altering a table.
ALTER TABLE ORDERS ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);
If CUSTOMERS table has already been created, then to add a CHECK constraint to AGE column, you
would write a statement similar to the following:
ALTER TABLE CUSTOMERS ADD CONSTRAINT myCheckConstraintCHECK(AGE >= 18);
SQL UNIQUE Constraint on ALTER TABLE
To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the following
SQL:
ALTERTABLEPersons ADD UNIQUE (P_Id)
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple
columns, use the following SQL syntax:
ALTERTABLEPersons
ADDCONSTRAINTuc_PersonIDUNIQUE(P_Id,LastName)
ALTERTABLEPersons
ALTERCOLUMNCitySETDEFAULT'SANDNES'
DROP
Removing a table from a database schema is easy. Just use a DROP TABLE <tablename>command. You
erase all the table‘s data as well as the metadata that defines the table in the data dictionary. It‘s almost as
if the table never existed. Eg Drop table Customers.
Delete Primary Key:-You can clear the primary key constraints from the table, Use Syntax:
ALTER TABLE CUSTOMERS DROP PRIMARY KEY PK_CUSTID;
To drop a FOREIGN KEY constraint, use the following SQL:
ALTER TABLE ORDERS DROP FOREIGN KEYCustomer_ID;
TodropaUNIQUEconstraint,usethefollowing SQL:
ALTERTABLEPersons DROPCONSTRAINTuc_PersonID
Zipcode INTEGER
VendorID INTEGER
CustomerID INTEGER
InvoiceDate DATE
InvoiceNumber Integer
ProductID INTEGER
Quantity INTEGER
Notice that some of the columns in the above Table contain the constraint primary key and NOT NULL.
These columns are either the primary keys of their respective tables or columns that you decide must
contain a value. A table‘s primary key must uniquely identify each row. To do that, the primary key must
contain a nonnull value in every row. The tables relate to each other through the columns that they have in
common.
The following list describes these relationships.
The CUSTOMER table bears a one-to-many relationship to the INVOICEtable. One customer can make
multiple purchases, generating multiple invoices. Each invoice, however, deals with one and only one
customer.
The INVOICE table bears a one-to-many relationship to the INVOICE_LINEtable. An invoice may have
multiple lines, but each line appears on one and only one invoice.
The PRODUCT table also bears a one-to-many relationship to the INVOICE_LINE table. A product may
appear on more than one line on one or more invoices. Each line, however, deals with one, and only
oneproduct.
The CUSTOMER table links to the INVOICE table by the common CustomerID column. The INVOICE
table links to the INVOICE_LINE table by the common InvoiceNumber column. The PRODUCT table
links to the INVOICE_LINE table by the common ProductID column. These links are what makes this
database a relational database.
Lap Test
Instruction: Given necessary tools and materials you are required to perform the
following tasks accordingly
Task 1: Create a database called Hospital
Task 2: Create a table called Doctor, Patient and medicine with their respected relations
Task 3: Display a relationship you have created
Unit Three: Data manipulation language
3.1. Overview of SQL data manipulation language commands
The DDL is the part of SQL that creates, modifies, or destroys database structures; it doesn‘t deal with the
data. The Data Manipulation Language (DML)is the part of SQL that operates on the data. Some DML
statements read likeordinary English-language sentences and are easy to understand. Because SQLgives
you very fine control of data, other DML statements can be fiendishly
complex. If a DML statement includes multiple expressions, clauses, predicates, or subqueries,
understanding what that statement is trying to do canbe a challenge.
3.2. Data insertion
SQL INSERT Query
The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Syntax:
There are two basic syntaxes of INSERT INTO statement as follows:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN) VALUES (value1, value2,
value3,...valueN);
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.
The SQL INSERT INTO syntax would be as follows:
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Example:
Following statements would create six records in CUSTOMERS table:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'Komal', 22, 'MP', 4500.00 );
You can create a record in CUSTOMERS table using second syntax as follows
INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
All the above statements would produce the following records in CUSTOMERS table:
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
"FirstName" columns:
The"Persons"tablewillnowlooklikethis:
P_Id LastName FirstName Address City
5 Tjessem Jakob
Lap Test
Instruction: Given necessary tools and materials you are required to perform the
following tasks accordingly
Task 1:Create a database for called AB_Supermarket
Task 2: Create and insert the following data to the Customers and customer_ordertable
Customer Table
Unit Four: Data query language
SELECTcolumn_name(s)
FROM table_name
and
SELECT*FROMtable_name
Note:SQLisnotcasesensitive.SELECTisthesameasselect.
An SQL SELECT Example, The "Persons" table:
SELECTLastName, FirstNameFROMPersons
Theresult-setwilllooklikethis:
LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari
SELECT * Example
SELECT*FROMPersons
NavigationinaResult-set
Mostdatabasesoftwaresystemsallownavigationintheresult-setwithprogrammingfunctions, like:
Move-To-First-Record, Get-Record-Content, Move-To-Next-Record, etc.
Programmingfunctionslikethesearenotapartofthistutorial.
1.3. Retrieval of data selectively
SQLSELECTDISTINCTStatement
Inatable,someofthecolumnsmaycontainduplicatevalues.Thisisnotaproblem,however, sometimes you will
want to list only the different (distinct) values in a table.
TheDISTINCTkeywordcanbeusedtoreturnonlydistinct(different)values.
SQL SELECT DISTINCT Syntax
SELECTDISTINCTcolumn_name(s) FROMtable_name
SELECTDISTINCTExample: The"Persons"table:
Sandnes
Stavanger
SELECTcolumn_name(s)
FROM table_name
WHEREcolumn_nameoperatorvalue
WHEREClauseExample
The"Persons"table:
SELECT*FROMPersons WHERECity='Sandnes'
QuotesaroundTextFields
SQLusessinglequotesaroundtextvalues(mostdatabasesystemswillalsoacceptdouble quotes).
Although,numericvaluesshouldnotbeenclosedinquotes. For
Thisiscorrect:
SELECT*FROMPersonsWHEREFirstName='Tove'
is wrong:
SELECT*FROMPersonsWHEREFirstName=Tove
text values:
Fornumericvalues:
Thisiscorrect:
SELECT*FROMPersonsWHEREYear=1965 This
is wrong:
SELECT*FROMPersonsWHEREYear='1965'
OperatorsAllowedintheWHERE Clause
WiththeWHEREclause,thefollowingoperatorscanbeused:
Operator Description
= Equal
<> Not equal
> Greaterthan
< Lessthan
>= Greaterthanorequal
<= Lessthan orequal
BETWEE Betweenaninclusiverange
N
LIKE Searchfora pattern
IN Ifyouknowtheexactvalueyouwanttoreturnforatleastoneofthe columns
Note:InsomeversionsofSQLthe<>operatormaybewrittenas!=
SQLAND&OR Operators
TheAND&ORoperatorsareusedtofilterrecordsbasedonmorethanonecondition.
TheANDoperatordisplaysarecordifboththefirstandthesecondconditionistrue.
TheORoperatordisplaysarecordifeitherthefirstconditionorthesecondconditionistrue.
ANDOperatorExample
The"Persons"table:
Theresult-setwilllooklikethis:
Theresult-setwilllooklikethis:
CombiningAND&OR
YoucanalsocombineANDandOR(useparenthesistoformcomplexexpressions).
Nowwewant toselect onlythepersonswiththelastnameequalto "Svendson"ANDthefirst name
equal to "Tove" OR to "Ola":
WeusethefollowingSELECTstatement:
SELECT*FROMPersonsWHERE LastName='Svendson'
AND(FirstName='Tove'ORFirstName='Ola')
Theresult-setwilllooklikethis:
SQLORDERBYKeyword
TheORDERBYkeywordisusedtosorttheresult-set.
TheORDERBYkeywordisusedtosorttheresult-setbyaspecifiedcolumn. The
ORDER BY keyword sort the records in ascending order by default.
If youwanttosorttherecordsinadescendingorder,youcanusetheDESCkeyword.
SQLORDERBYSyntax
SELECTcolumn_name(s)
FROM table_name
ORDERBYcolumn_name(s)ASC|DESC
ORDERBYExample
The"Persons"table:
SELECT*FROMPersons
ORDER BY LastName
Nowwewanttoselectallthepersonsfromthetableabove,however,wewanttosortthe persons by their last name.
WeusethefollowingSELECTstatement:
Theresult-setwilllooklikethis:
ORDERBYDESCExample
Nowwewanttoselectallthepersonsfromthetableabove,however,wewanttosortthe persons descending
by their last name.
WeusethefollowingSELECTstatement:
Theresult-setwilllooklikethis:
SQLUPDATEStatement
TheUPDATEstatementisusedtoupdateexistingrecordsinatable.
UPDATEtable_name
SETcolumn1=value,column2=value2,... WHERE
some_column=some_value
SQLUPDATESyntax
Note:NoticetheWHEREclauseintheUPDATEsyntax.TheWHEREclausespecifieswhich record or
records that should be updated. If you omit the WHERE clause, all records will be updated!
SQLUPDATEExample
The"Persons"table:
5 Tjessem Jakob
Nowwewanttoupdatetheperson"Tjessem,Jakob"inthe"Persons"table. We use
the following SQL statement:
UPDATEPersons
SETAddress='Nissestien67',City='Sandnes'
WHERELastName='Tjessem'ANDFirstName='Jakob'
The"Persons"tablewillnowlooklikethis:
SQLUPDATEWarning
Becarefulwhenupdatingrecords. IfwehadomittedtheWHEREclauseintheexampleabove, like this:
UPDATEPersons
SETAddress='Nissestien67',City='Sandnes'
The"Persons"tablewouldhavelookedlikethis:
SQLDELETEStatement
TheDELETEstatementisusedtodeleterows/recordsinatable.
SQLDELETESyntax
Note:NoticetheWHEREclauseintheDELETEsyntax.TheWHEREclausespecifieswhich record or
records that should be deleted. If you omit the WHERE clause, all records will be deleted!
SQLDELETEExample
The"Persons"table:
DELETEFROMPersons
WHERELastName='Tjessem'ANDFirstName='Jakob'
Nowwewanttodeletetheperson"Tjessem,Jakob"inthe"Persons"table. We use
the following SQL statement:
The"Persons"tablewillnowlooklikethis:
DeleteAllRows
DELETEFROMtable_nameor
DELETE*FROMtable_name
Note:Beverycarefulwhendeletingrecords.Youcannotundothisstatement!
1. CharacterandStringComparisonOperators:
=(Equalto):Comparesiftwocharacterorstringvaluesareidentical.
!=or<>(Notequalto):Checksiftwocharacterorstringvaluesarenotidentical.
LIKE:Comparesacharacterorstringvaluewith apattern,oftenusingwildcardcharacters
(% and _).
Example:
DateandTimeComparisonOperators:
=(Equalto):Comparesiftwodateortimevaluesareequal.
!=or<>(Notequalto):Comparesiftwodateortimevaluesarenotequal.
<(Lessthan):Checksifonedateortimevalueisearlierthananother.
>(Greaterthan):Checksifonedateortimevalueislaterthananother.
<=(Lessthanorequalto):Checksifonedateortimevalueisearlierthanorequalto another.
>=(Greaterthanorequalto):Checksifonedateortimevalueislaterthanorequalto another.
Example:
When using these comparison operators in your SQL queries, be sure to match the data types
appropriately. For example, when comparing dates, make sure the date format matches the one
used in your database. Also, consider the collation (sorting and comparison rules) for character
and string data when using comparison operators for text-based data.
Tocontroltheorderofevaluationandensurecorrectprecedence, youcan useparenthesesto group
conditions.
Example:
SELECT*FROMemployeesWHERE(age>=30ORexperience_years>=5)AND department =
'Engineering';
Inthisquery,theconditionsinsidetheparenthesesareevaluatedfirst,andthentheAND condition is applied to
the results.
Using parentheses is especially important when combining AND and OR operators in the same
query to make your intentions explicit and avoid unexpected behavior.
Understandingthe correctprecedenceandusingparentheseswhennecessaryis crucialtoensure that
your SQL queries produce the desired results and correctly evaluate complex conditions.
2. Checkingforarangeofvalues
Youcanusecomparisonoperatorstofilterrowsbasedonarangeofvalues.Forexample,to retrieve
products with prices between $50 and $100:
SELECT*FROMproductsWHEREprice>=50ANDprice<=100;
Thisqueryretrievesrows fromthe"products"tablewherethe"price"is greaterthanorequalto 50
and less than or equal to 100.
Selectingvaluesfromalist
You can use the IN operator to filter rows based on a list of values. For example, to retrieve
orders from customers in New York or California:
SELECT*FROMordersWHEREcustomer_stateIN('NewYork','California');
This query retrieves rows from the "orders" table where the "customer_state" is either 'New
York' or 'California'.
CheckingforValuesthatMatchaPattern
You can use the LIKE operator with wildcard characters to match values that fit a specific
pattern. For example, to retrieve products with names starting with 'Laptop':
SELECT*FROMproductsWHEREproduct_nameLIKE'Laptop%';
This query retrieves rows from the "products" table where the "product_name" starts with
'Laptop'. The '%' wildcard matches any sequence of characters, so it matches 'Laptop,' 'Laptop
Pro,' 'Laptop 2023,' and so on.
You can also use the NOT LIKE operator to exclude rows that match a particular pattern. For
example, to retrieve products with names that don't start with 'Accessory':
SELECT*FROMproductsWHEREproduct_nameNOTLIKE'Accessory%';
Thisqueryretrievesrowswherethe"product_name"doesnotstartwith'Accessory'.
These SQL techniques are commonly used to filter and retrieve specific data from a database
based on various criteria, making it easier to work with the data that meets your specific
requirements.
Takingactiontoexecutenullvaluesfromaqueryresult
In SQL, you can take action to handle and filter out null values from a queryresult using the IS
NULL and IS NOT NULL operators. Here's how you can use them:
3. FilteringRowswithNullValues(ISNULL):
Toretrieverowsthatcontainnullvaluesinaspecificcolumn,youcanusetheISNULL
operator.Forexample,toretrieveallproductswithnullvaluesinthe"description"column:
Thisquerywillreturnrowswherethe"description"columnisnull.
FilteringRowswithoutNullValues(ISNOTNULL):
To retrieve rows that do not contain null values in a specific column, you can use the IS NOT
NULL operator. For example, to retrieve all products with a non-null value in the "price"
column:
SELECT*FROMproductsWHEREpriceISNOTNULL;
Thisquerywillreturnrowswherethe"price"columnisnotnull.
HandlingNullValuesintheResult(COALESCE):
If you want to replace null values in the query result with a specific default value, you can use
the COALESCE function. For example, if you want to replace null values in the "description"
column with "No description available":
SELECTproduct_name,COALESCE(description,'Nodescriptionavailable')ASdescription
FROM products;
This query uses the COALESCE function to replace null values with the specified default
value in the result set.
Handling null values is important to ensure the accuracy and completeness of your query
results. Themethodsmentioned aboveallow youto filter andmanagenull values effectivelyin
yourSQL queries.
1.4. Working with functions
Using arithmetical operators with the correctprecedence
Arithmetic Operators
You can use arithmetic operators in Multidimensional Expressions (MDX) for any
arithmeticcomputations, including addition, subtraction, multiplication, and division.
MDXsupportsthearithmeticoperatorslistedinthefollowingtable.
Operator Description
+ (Add) Addstwonumbers.
/ (Divide) Dividesonenumberbyanothernumber.
*(Multiply) Multipliestwonumbers.
- (Subtract) Subtractstwonumbers.
^(Power) Raisesonenumberbyanothernumber.
ThefollowingrulesdeterminetheorderofprecedenceforarithmeticoperatorsinanMDX expression:
Whenthereismorethanonearithmeticoperatorinanexpression,MDXperforms
multiplication and division first, followed by subtraction and addition.
Whenallarithmeticoperatorsinanexpressionhavethesamelevelofprecedence,the order
of execution is left to right.
Expressionswithinparenthesestakeprecedenceoverallotheroperations.
In SQL, you can perform arithmetic operations using operators such as +, -, *, and /. It's
important to understand operator precedence when combining multiple operators in an
expression.
Example: Suppose you have a table called "Products" with columns "Price" and
"Quantity."You want to calculate the total cost for each product, considering the unit price and
quantity. The SQL statement would be:
SELECTProductName,(Price*Quantity)ASTotalCost FROM Products;
In this example, the * operator is used to multiply the "Price" and "Quantity" columns to obtain
the "TotalCost."
UsingStringFunctionsandOperators:
SQL provides various string functions and operators for working with text data. For
instance,you can use the CONCAT function to concatenate strings.
Example:
Suppose you have a tablecalled "Employees"with columns "FirstName" and "LastName."You
want to create a single string representing the full name. The SQL statement would be:
Example:
Suppose you have a table called "Orders" with a "TotalAmount" column. You want to calculate
the square root of the total amount. The SQL statement would be:
SELECTOrderID,SQRT(TotalAmount)ASSquareRootAmount FROM Orders;
Inthisexample,theSQRTfunctioncalculatesthesquarerootofthe"TotalAmount."
UsingDateFunctions:
SQLprovidesvariousdatefunctionsforworkingwithdateandtimedata. Example:
Suppose you have a table called "Events" with a "EventDate" column, and you want to find the
events that occurred within the last 30 days. The SQL statement would be:
SELECTEventName,EventDate FROM Events WHEREEventDate>=DATEADD(day,-
30,GETDATE());
Inthisexample,theDATEADDfunctionsubtracts30daysfromthecurrentdate (GETDATE()), and the
WHERE clause filters events that occurred after that date.
UsingSQLAggregateFunctions:
SQLaggregatefunctionsareusedtoperformcalculationsonsetsofvalues.
AVG()-TheAVG()functionreturnstheaveragevalueofanumericcolumn.
AVG()Syntax
SELECTAVG(column_name) FROM table_nameWHEREcondition;
Example
COUNT()–TheCOUNT()functionreturnsthenumberofrowsthatmatchesaspecified criterion.
COUNT()Syntax
SELECTCOUNT(column_name) FROM table_nameWHEREcondition;
Example
WHEREcolumn_nameoperatorvalue
GROUPBYcolumn_name
SQLGROUPBYExample1
Wehavethefollowing"Orders"table:
Nowwewanttofindthetotalsum(totalorder)ofeachcustomer.
WewillhavetousetheGROUPBYstatementtogroupthecustomers. We use the following SQL
statement:
SELECTCustomer,SUM(OrderPrice)FROMOrders
GROUPBYCustomer
Theresult-setwilllooklikethis:
Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000
Nowwewanttofindifthecustomers"Hansen"or"Jensen"haveatotalorderofmorethan 1500.
Having clause
WeaddanordinaryWHEREclausetotheSQLstatement:
SELECTCustomer,SUM(OrderPrice)FROMOrders
GROUPBYCustomer
HAVINGSUM(OrderPrice)>1500
Theresult-setwilllooklikethis
Customer SUM(OrderPrice)
Hansen 2000
Jensen 2000
WecanalsousetheGROUPBYstatementonmorethanonecolumn,likethis:
Suppose you have a table called "Sales" with columns "Product," "Region," and "Revenue." To
aggregate data by both "Product" and "Region" and calculate the total revenue for each
combination, you can use the following SQL statement:
In this example, the data is grouped by both "Product" and "Region," and the SUM function
is applied to calculate the total revenue for each group.
SortingAggregateDatainQueryOutput:
You can sort the aggregate data in the query output using the ORDER BY clause. This
allows you to specify the order in which the results should be displayed.
Use ORDER BY if you want to order rows according to a value returned by an aggregate
function likeSUM(). The ORDER BY operator is followed by the aggregate function (in
our example,SUM()). DESC is placed after this function to specify a descending sort order.
Thus, the highest aggregate values are displayed first, then progressively lower values are
displayed. To sort inascendingorder, you can specifyASC or simplyomit eitherkeyword, as
ascendingis the default sort order.
Example1:
Continuing with the "Sales" table, if you want to see the total revenue for each product and
region combination, sorted in descending order of revenue, you can use the following SQL
statement:
In this example, the data is first aggregated, and then the results are sorted in descending
order of the "TotalRevenue" column.
FilteringAggregateDataUsingtheHAVINGClause:
The HAVING clause is used to filter the results of aggregate functions. It allows you to specify
conditions that the aggregated data must meet.
SQLHAVINGSyntax
SELECTcolumn_name,aggregate_function(column_name)
FROMtable_name
WHEREcolumn_nameoperatorvalue
GROUPBYcolumn_name
HAVINGaggregate_function(column_name)operatorvalue
SQLHAVINGExample1
Wehavethefollowing"Orders"table:
Nilsen 1700
Example2:
Supposeyouwanttofindproduct-regioncombinationswithatotalrevenuegreaterthan
$10,000.YoucanusethefollowingSQLstatement:
SELECTProduct,Region,SUM(Revenue)ASTotalRevenue FROM Sales
GROUP BY Product, Region
HAVINGTotalRevenue>10000;
In this example, the HAVING clause filters the results to include only those
combinationswhere the "TotalRevenue" is greater than $10,000.
These SQLstatements demonstrate how to aggregate data, sort the results, and filter
aggregated datausingthe GROUP BY,ORDER BY, and HAVING clauses, respectively.
Theseclausesare essential for summarizing and manipulating data in SQL queries.
1.5. Working with subqueries
1.5.1 Single row subquery
SQL Sub Queries
A Sub query or Inner query or Nested query is a query within another SQL query and embedded
within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further restrict
the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with
the operators like =, <, >, >=, <=, IN, BETWEEN etc.
There are a few rules that subqueries must follow:
Sub queries must be enclosed within parentheses.
A sub query can have only one column in the SELECT clause, unless multiple
columns are in the main query
for the sub query to compare its selected columns.
An ORDER BY cannot be used in a subquery, although the main query can use
an ORDER BY. The GROUP
BY can be used to perform the same function as the ORDER BY in a subquery.
Sub queries that return more than one row can only be used with multiple value
operators, such as the IN operator.
The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOBor NCLOB.
A subquery cannot be immediately enclosed in a set function.
The BETWEEN operator cannot be used with a subquery; however, theBETWEEN
operator can be used within the subquery.Subqueries with the SELECT Statement:
Subqueries are most frequently used with the SELECT statement. The basic syntax
is as follows:
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR