0% found this document useful (0 votes)
36 views23 pages

Select From Where Select From Where Select From Select From Where Select From Select From Select From Where IS NOT Null Order BY Desc Where

This document contains questions and answers about various SQL concepts like joins, select statements, aggregation functions, grouping, distinct values, inserting records, updating records, deleting records, cursors and triggers.

Uploaded by

Amar Deo
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
36 views23 pages

Select From Where Select From Where Select From Select From Where Select From Select From Select From Where IS NOT Null Order BY Desc Where

This document contains questions and answers about various SQL concepts like joins, select statements, aggregation functions, grouping, distinct values, inserting records, updating records, deleting records, cursors and triggers.

Uploaded by

Amar Deo
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 23

SELECT score,player FROM scores WHERE score=(SELECT max(score) FROM scores

WHERE score< (SELECT max(score) FROM scores));

SELECT max(sal) FROM emp WHERE sal< (SELECT max(sal) FROM emp)
SELECT min(sal) FROM (SELECT sal FROM emp WHERE sal IS NOT NULL ORDER BY sal
DESC) WHERE rownum<=&rownum;
select salary from emp e1 where (n-1)=(select count(*)
from emp where salary > e1.salary )

Q: What is a join and explain different types of joins.


A: Joins are used in queries to explain how different tables are related. Joins also let you
select data from a table depending upon data from another table.

Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further
classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

INNER JOIN

Inner join shows matches only when they exist in both tables. Example in the below SQL
there are two tables Customers and Orders and the inner join in made on
Customers.Customerid and Orders.Customerid. So this SQL will only give you result with
customers who have orders. If the customer does not have order, it will not display that
record.

SELECT Customers.*, Orders.* FROM Customers INNER JOIN Orders ON


Customers.CustomerID =Orders.CustomerID

LEFT OUTER JOIN

Left join will display all records in left table of the SQL statement. In SQL below customers
with or without orders will be displayed. Order data for customers without orders appears as
NULL values. For example, you want to determine the amount ordered by each customer
and you need to see who has not ordered anything as well. You can also see the LEFT
OUTER JOIN as a mirror image of the RIGHT OUTER JOIN (Is covered in the next section) if
you switch the side of each table.

SELECT Customers.*, Orders.* FROM Customers LEFT OUTER JOIN Orders ON


Customers.CustomerID =Orders.CustomerID

RIGHT OUTER JOIN

Right join will display all records in right table of the SQL statement. In SQL below all orders
with or without matching customer records will be displayed. Customer data for orders
without customers appears as NULL values. For example, you want to determine if there are
any orders in the data with undefined CustomerID values (say, after a conversion or
something like it). You can also see the RIGHT OUTER JOIN as a mirror image of the LEFT
OUTER JOIN if you switch the side of each table.

SELECT Customers.*, Orders.* FROM Customers RIGHT OUTER JOIN Orders ON


Customers.CustomerID =Orders.CustomerID

Q: What is SELECT statement?


A: The SELECT statement lets you select a set of values from a table in a database. The
values selected from the database table would depend on the various conditions that are
specified in the SQL query.

Q: How can you compare a part of the name rather than the entire name?
A: SELECT * FROM people WHERE empname LIKE '%ab%'
Would return a recordset with records consisting empname the sequence 'ab' in
empname .
 
Q: What is the INSERT statement?
A: The INSERT statement lets you insert information into a database.

Q: How do you delete a record from a database?


A: Use the DELETE statement to remove records or any particular column values from a
database.
 
Q: How could I get distinct entries from a table?
A: The SELECT statement in conjunction with DISTINCT lets you select a set of distinct
values from a table in a database. The values selected from the database table would of
course depend on the various conditions that are specified in the SQL query. Example
SELECT DISTINCT empname FROM emptable
 
Q: How to get the results of a Query sorted in any order?
A: You can sort the results and return the sorted results to your program by using ORDER
BY keyword thus saving you the pain of carrying out the sorting yourself. The ORDER BY
keyword is used for sorting.

SELECT empname, age, city FROM emptable ORDER BY empname


 
Q: How can I find the total number of records in a table?
A: You could use the COUNT keyword , example

SELECT COUNT(*) FROM emp WHERE age>40


 
Q: What is GROUP BY?
A: The GROUP BY keywords have been added to SQL because aggregate functions (like
SUM) return the aggregate of all column values every time they are called. Without the
GROUP BY functionality, finding the sum for each individual group of column values was
not possible.
 
Q: What is the difference among "dropping a table", "truncating a table" and
"deleting all records" from a table.
A: Dropping :  (Table structure  + Data are deleted), Invalidates the dependent
objects ,Drops the indexes

Truncating:  (Data alone deleted), Performs an automatic commit, Faster than delete

Delete : (Data alone deleted), Doesn’t perform automatic commit


 
Q: What are the Large object types suported by Oracle?
A: Blob and Clob.
 
Q: Difference between a "where" clause and a "having" clause.
A: Having clause is used only with group functions whereas Where is not used with.

 
Q: What's the difference between a primary key and a unique key?
A: Both primary key and unique enforce uniqueness of the column on which they are
defined. But by default primary key creates a clustered index on the column, where are
unique creates a nonclustered index by default. Another major difference is that, primary
key doesn't allow NULLs, but unique key allows one NULL only.

 
Q: What are cursors? Explain different types of cursors. What are the
disadvantages of cursors? How can you avoid cursors?
A: Cursors allow row-by-row prcessing of the resultsets.

Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for
more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a
network roundtrip, where as a normal SELECT query makes only one rowundtrip,
however large the resultset is. Cursors are also costly because they require more
resources and temporary storage (results in more IO operations). Furthere, there are
restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors.
 
Q: What are triggers? How to invoke a trigger on demand?
A: Triggers are special kind of stored procedures that get executed automatically when an
INSERT, UPDATE or DELETE operation takes place on a table.

Triggers can't be invoked on demand. They get triggered only when an associated action
(INSERT, UPDATE, DELETE) happens on the table on which they are defined.

Triggers are generally used to implement business rules, auditing. Triggers can also be
used to extend the referential integrity checks, but wherever possible, use constraints for
this purpose, instead of triggers, as constraints are much faster.

Q: What is a join and explain different types of joins.


A: Joins are used in queries to explain how different tables are related. Joins also let you
select data from a table depending upon data from another table.

Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further
classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.
 
Q: What is a self join?
A: Self join is just like any other join, except that two instances of the same table will be
joined in the query.

The SQL SELECT INTO statement is used to select data from a SQL database table and to insert it
to a different table at the same time.

The general SQL SELECT INTO syntax looks like this:


SELECT Column1, Column2, Column3, 
INTO Table2
FROM Table1
The list of column names after the SQL SELECT command determines which columns will be copied,
and the table name after the SQL INTO keyword specifies to which table to copy those rows.

If we want to make an exact copy of the data in our Customers table, we need the following SQL
SELECT INTO statement:

SELECT *
INTO Customers_copy
FROM Customers

The SQL DISTINCT clause is used together with the SQL SELECT keyword, to return a dataset with
unique entries for certain database table column.

We will use our Customers database table to illustrate the usage of SQL DISTINCT.

FirstName LastName Email DOB Phone


John Smith John.Smith@yahoo.com 2/4/1968 626 222-2222
Steven Goldfish goldfish@fishhere.net 4/4/1974 323 455-4545
Paula Brown pb@herowndomain.org 5/24/1978 416 323-3232
James Smith jim@supergig.co.uk 20/10/1980 416 323-8888

For example if we want to select all distinct surnames from our Customers table, we will use the
following SQL DISTINCT statement:

SELECT DISTINCT LastName


FROM Customers 

The SQL INSERT INTO syntax has 2 main forms and the result of either of them is adding a new
row into the database table.

The first syntax form of the INSERT INTO SQL clause doesn't specify the column names where the
data will be inserted, but just their values:

INSERT INTO Table1


VALUES (value1, value2, value3…)

The second form of the SQL INSERT INTO command, specifies both the columns and the values to
be inserted in them:

INSERT INTO Table1 (Column1, Column2, Column3…)


VALUES (Value1, Value2, Value3…)

As you might already have guessed, the number of the columns in the second INSERT INTO syntax
form must match the number of values into the SQL statement, otherwise you will get an error.

If we want to insert a new row into our Customers table, we are going to use one of the following 2
SQL statements:
INSERT INTO Customers
VALUES ('Peter', 'Hunt', 'peter.hunt@tgmail.net', '1/1/1974', '626 888-8888')

INSERT INTO Customers (FirstName, LastName, Email, DOB, Phone)


VALUES ('Peter', 'Hunt', 'peter.hunt@tgmail.net', '1/1/1974', '626 888-8888')

The SQL IN clause allows you to specify discrete values in your SQL WHERE search criteria.

THE SQL IN syntax looks like this:

SELECT Column1, Column2, Column3, …


FROM Table1
WHERE Column1 IN (Valu1, Value2, …) 

he SQL BETWEEN & AND keywords define a range of data between 2 values.

The SQL BETWEEN syntax looks like this:

SELECT Column1, Column2, Column3, …


FROM Table1
WHERE Column1 BETWEEN Value1 AND Value2 

SQL aliases can be used with database tables and with database table columns, depending on task
you are performing.

SQL column aliases are used to make the output of your SQL queries easy to read and more
meaningful:

SELECT Employee, SUM(Hours) As SumHoursPerEmployee


FROM EmployeeHours
GROUP BY Employee 

In the example above we created SQL alias SumHoursPerEmployee and the result of this SQL query
will be the following:

Employee SumHoursPerEmployee
John Smith 25
Allan Babel 24
Tina Crown 27

The SQL GROUP BY statement is used along with the SQL aggregate functions like SUM to provide
means of grouping the result dataset by certain database table column(s).

The best way to explain how and when to use the SQL GROUP BY statement is by example, and
that’s what we are going to do.

Consider the following database table called EmployeeHours storing the daily hours for each
employee of a factious company:
Employee Date Hours
John Smith 5/6/2004 8
Allan Babel 5/6/2004 8
Tina Crown 5/6/2004 8
John Smith 5/7/2004 9
Allan Babel 5/7/2004 8
Tina Crown 5/7/2004 10
John Smith 5/8/2004 8
Allan Babel 5/8/2004 8
Tina Crown 5/8/2004 9

If the manager of the company wants to get the simple sum of all hours worked by all employees,
he needs to execute the following SQL statement:

SELECT SUM (Hours)


FROM EmployeeHours 

But what if the manager wants to get the sum of all hours for each of his employees?
To do that he need to modify his SQL query and use the SQL GROUP BYstatement:

SELECT Employee, SUM (Hours)


FROM EmployeeHours
GROUP BY Employee 

The result of the SQL expression above will be the following:

Employee Hours
John Smith 25
Allan Babel 24
Tina Crown 27

As you can see we have only one entry for each employee, because we are grouping by the
Employee column.

The SQL GROUP BY clause can be used with other SQL aggregate functions, for example SQL AVG:

SELECT Employee, AVG(Hours)


FROM EmployeeHours
GROUP BY Employee 

The result of the SQL statement above will be:

Employee
Hours
John Smith
8.33

Allan Babel
8

Tina Crown
9

The SQL HAVING clause is used to restrict conditionally the output of a SQL statement, by a SQL
aggregate function used in your SELECT list of columns.

You can't specify criteria in a SQL WHERE clause against a column in the SELECT list for which SQL
aggregate function is used. For example the following SQL statement will generate an error:

SELECT Employee, SUM (Hours)


FROM EmployeeHours
WHERE SUM (Hours) > 24
GROUP BY Employee 

The SQL HAVING clause is used to do exactly this, to specify a condition for an aggregate function
which is used in your query:

SELECT Employee, SUM (Hours)


FROM EmployeeHours
GROUP BY Employee
HAVING SUM (Hours) > 24 

The above SQL statement will select all employees and the sum of their respective hours, as long
as this sum is greater than 24. The result of the SQL HAVING clause can be seen below:

Employee Hours
John Smith 25
Tina Crown 27

SQL Wildcards 
SQL wildcards can substitute for one or more characters when searching for data in a database.

SQL wildcards must be used with the SQL LIKE operator.

With SQL, the following wildcards can be used:

Wildcard Description
% A substitute for zero or more characters
_ A substitute for exactly one character
[charlist] Any single character in charlist
[^charlist] Any single character not in charlist

or

[!charlist]

SQL Wildcard Examples


We have the following "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Using the % Wildcard


Now we want to select the persons living in a city that starts with "sa" from the "Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE City LIKE 'sa%'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

Next, we want to select the persons living in a city that contains the pattern "nes" from the "Persons"
table.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE City LIKE '%nes%'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

Using the _ Wildcard


Now we want to select the persons with a first name that starts with any character, followed by "la"
from the "Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE FirstName LIKE '_la'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes

Next, we want to select the persons with a last name that starts with "S", followed by any character,
followed by "end", followed by any character, followed by "on" from the "Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE LastName LIKE 'S_end_on'

The result-set will look like this:

P_Id LastName FirstName Address City


2 Svendson Tove Borgvn 23 Sandnes

Using the [charlist] Wildcard


Now we want to select the persons with a last name that starts with "b" or "s" or "p" from the
"Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE LastName LIKE '[bsp]%'

The result-set will look like this:

P_Id LastName FirstName Address City


2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Next, we want to select the persons with a last name that do not start with "b" or "s" or "p" from the
"Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE LastName LIKE '[!bsp]%'

The result-set will look like this:


P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes

he IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.

SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)

IN Operator Example
The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the persons with a last name equal to "Hansen" or "Pettersen" from the table
above.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE LastName IN ('Hansen','Pettersen')

The result-set will look like this:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

The BETWEEN operator is used in a WHERE clause to select a range of data between
two values.

The BETWEEN Operator


The BETWEEN operator selects a range of data between two values. The values can be numbers, text,
or dates.

SQL BETWEEN Syntax


SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2

BETWEEN Operator Example


The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the persons with a last name alphabetically between "Hansen" and "Pettersen"
from the table above.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE LastName
BETWEEN 'Hansen' AND 'Pettersen'

The result-set will look like this:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

Note: The BETWEEN operator is treated differently in different databases!

In some databases, persons with the LastName of "Hansen" or "Pettersen" will not be listed, because
the BETWEEN operator only selects fields that are between and excluding the test values.

In other databases, persons with the LastName of "Hansen" or "Pettersen" will be listed, because the
BETWEEN operator selects fields that are between and including the test values.

And in other databases, persons with the LastName of "Hansen" will be listed, but "Pettersen" will not
be listed (like the example above), because the BETWEEN operator selects fields between the test
values, including the first test value and excluding the last test value.
Therefore: Check how your database treats the BETWEEN operator.

Example 2
To display the persons outside the range in the previous example, use NOT BETWEEN:

SELECT * FROM Persons


WHERE LastName
NOT BETWEEN 'Hansen' AND 'Pettersen'

The result-set will look like this:

P_Id LastName FirstName Address City

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

SQL joins are used to query data from two or more tables, based on a relationship
between certain columns in these tables.

SQL JOIN
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a
relationship between certain columns in these tables.

Tables in a database are often related to each other with keys.

A primary key is a column (or a combination of columns) with a unique value for each row. Each
primary key value must be unique within the table. The purpose is to bind data together, across
tables, without repeating all of the data in every table.

Look at the "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Note that the "P_Id" column is the primary key in the "Persons" table. This means that no two rows
can have the same P_Id. The P_Id distinguishes two persons even if they have the same name.

Next, we have the "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15

Note that the "O_Id" column is the primary key in the "Orders" table and that the "P_Id" column
refers to the persons in the "Persons" table without using their names.

Notice that the relationship between the two tables above is the "P_Id" column.

Different SQL JOINs


Before we continue with examples, we will list the types of JOIN you can use, and the differences
between them.

 JOIN: Return rows when there is at least one match in both tables
 LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
 RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left
table
 FULL JOIN: Return rows when there is a match in one of the tables

Indexes
An index can be created in a table to find data more quickly and efficiently.

The users cannot see the indexes, they are just used to speed up searches/queries.

Note: Updating a table with indexes takes more time than updating a table without (because the
indexes also need an update). So you should only create indexes on columns (and tables) that will be
frequently searched against.

SQL CREATE INDEX Syntax

Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name


ON table_name (column_name)

SQL CREATE UNIQUE INDEX Syntax

Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name


ON table_name (column_name)

Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the
syntax for creating indexes in your database.

CREATE INDEX Example


The SQL statement below creates an index named "PIndex" on the "LastName" column in the
"Persons" table:

CREATE INDEX PIndex


ON Persons (LastName)

If you want to create an index on a combination of columns, you can list the column names within the
parentheses, separated by commas:

CREATE INDEX PIndex


ON Persons (LastName, FirstName)

The ALTER TABLE Statement


The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

SQL ALTER TABLE Syntax

To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype

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

To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name


ALTER COLUMN column_name datatype

SQL ALTER TABLE Example


Look at the "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger


Now we want to add a column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons


ADD DateOfBirth date

Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data type
specifies what type of data the column can hold. For a complete reference of all the data types
available in MS Access, MySQL, and SQL Server, go to our complete Data Types reference.

The "Persons" table will now like this:

P_Id LastName FirstName Address City DateOfBirth

1 Hansen Ola Timoteivn 10 Sandnes  

2 Svendson Tove Borgvn 23 Sandnes  

3 Pettersen Kari Storgt 20 Stavanger  

Change Data Type Example


Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons


ALTER COLUMN DateOfBirth year

Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two-digit or
four-digit format.

DROP COLUMN Example


Next, we want to delete the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons


DROP COLUMN DateOfBirth

The "Persons" table will now like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

SQL CREATE VIEW Statement


In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one or
more real tables in the database.

You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the
data were coming from one single table.

SQL CREATE VIEW Syntax


CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

Note: A view always shows up-to-date data! The database engine recreates the data, using the view's
SQL statement, every time a user queries a view.

SQL CREATE VIEW Examples


If you have the Northwind database you can see that it has several views installed by default.

The view "Current Product List" lists all active products (products that are not discontinued) from the
"Products" table. The view is created with the following SQL:

CREATE VIEW [Current Product List] AS


SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No

We can query the view above as follows:

SELECT * FROM [Current Product List]

Another view in the Northwind sample database selects every product in the "Products" table with a
unit price higher than the average unit price:

CREATE VIEW [Products Above Average Price] AS


SELECT ProductName,UnitPrice
FROM Products
WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products)

We can query the view above as follows:

SELECT * FROM [Products Above Average Price]

Another view in the Northwind database calculates the total sale for each category in 1997. Note that
this view selects its data from another view called "Product Sales for 1997":

CREATE VIEW [Category Sales For 1997] AS


SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName

We can query the view above as follows:

SELECT * FROM [Category Sales For 1997]

We can also add a condition to the query. Now we want to see the total sale only for the category
"Beverages":

SELECT * FROM [Category Sales For 1997]


WHERE CategoryName='Beverages'

SQL Updating a View


You can update a view by using the following syntax:

SQL CREATE OR REPLACE VIEW Syntax


CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

Now we want to add the "Category" column to the "Current Product List" view. We will update the
view with the following SQL:

CREATE VIEW [Current Product List] AS


SELECT ProductID,ProductName,Category
FROM Products
WHERE Discontinued=No
SQL Dropping a View
You can delete a view with the DROP VIEW command.

SQL DROP VIEW Syntax


DROP VIEW view_name

SQL Server Data Types


Character strings:

Data type Description Storage


char(n) Fixed-length character string. Maximum 8,000 characters n
varchar(n) Variable-length character string. Maximum 8,000 characters  
varchar(max) Variable-length character string. Maximum 1,073,741,824 characters  
text Variable-length character string. Maximum 2GB of text data  

Unicode strings:

Data type Description Storage


nchar(n) Fixed-length Unicode data. Maximum 4,000 characters  
nvarchar(n) Variable-length Unicode data. Maximum 4,000 characters  
nvarchar(max) Variable-length Unicode data. Maximum 536,870,912 characters  
ntext Variable-length Unicode data. Maximum 2GB of text data  

Binary types:

Data type Description Storage


bit Allows 0, 1, or NULL  
binary(n) Fixed-length binary data. Maximum 8,000 bytes  
varbinary(n) Variable-length binary data. Maximum 8,000 bytes  
varbinary(max) Variable-length binary data. Maximum 2GB  
image Variable-length binary data. Maximum 2GB  

Number types:

Data type Description Storage


tinyint Allows whole numbers from 0 to 255 1 byte
smallint Allows whole numbers between -32,768 and 32,767 2 bytes
int Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes
bigint Allows whole numbers between -9,223,372,036,854,775,808 and 8 bytes
9,223,372,036,854,775,807
decimal(p,s) Fixed precision and scale numbers. 5-17
bytes
Allows numbers from -10^38 +1 to 10^38 –1.

The p parameter indicates the maximum total number of digits that


can be stored (both to the left and to the right of the decimal point). p
must be a value from 1 to 38. Default is 18.

The s parameter indicates the maximum number of digits stored to the


right of the decimal point. s must be a value from 0 to p. Default value
is 0
numeric(p,s) Fixed precision and scale numbers. 5-17
bytes
Allows numbers from -10^38 +1 to 10^38 –1.

The p parameter indicates the maximum total number of digits that


can be stored (both to the left and to the right of the decimal point). p
must be a value from 1 to 38. Default is 18.

The s parameter indicates the maximum number of digits stored to the


right of the decimal point. s must be a value from 0 to p. Default value
is 0
smallmoney Monetary data from -214,748.3648 to 214,748.3647 4 bytes
money Monetary data from -922,337,203,685,477.5808 to 8 bytes
922,337,203,685,477.5807
float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308. 4 or 8
bytes
The n parameter indicates whether the field should hold 4 or 8 bytes.
float(24) holds a 4-byte field and float(53) holds an 8-byte field.
Default value of n is 53.
real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes

Date types:

Data type Description Storage


datetime From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 8 bytes
milliseconds
datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 100 6-8
nanoseconds bytes
smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute 4 bytes
date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes
time Store a time only to an accuracy of 100 nanoseconds 3-5
bytes
datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10
bytes
timestamp Stores a unique number that gets updated every time a row gets  
created or modified. The timestamp value is based upon an internal
clock and does not correspond to real time. Each table may have only
one timestamp variable

Other data types:

Data type Description


sql_variant Stores up to 8,000 bytes of data of various data types, except text, ntext, and
timestamp
uniqueidentifier Stores a globally unique identifier (GUID)
xml Stores XML formatted data. Maximum 2GB
cursor Stores a reference to a cursor used for database operations
table Stores a result-set for later processing

SQL has many built-in functions for performing calculations on data.

SQL Aggregate Functions


SQL aggregate functions return a single value, calculated from values in a column.

Useful aggregate functions:

 AVG() - Returns the average value


 COUNT() - Returns the number of rows
 FIRST() - Returns the first value
 LAST() - Returns the last value
 MAX() - Returns the largest value
 MIN() - Returns the smallest value
 SUM() - Returns the sum

SQL Scalar functions


SQL scalar functions return a single value, based on the input value.

Useful scalar functions:

 UCASE() - Converts a field to upper case


 LCASE() - Converts a field to lower case
 MID() - Extract characters from a text field
 LEN() - Returns the length of a text field
 ROUND() - Rounds a numeric field to the number of decimals specified
 NOW() - Returns the current system date and time
 FORMAT() - Formats how a field is to be displayed

SQL Statement Syntax


AND / OR SELECT column_name(s)
FROM table_name
WHERE condition
AND|OR condition
ALTER TABLE ALTER TABLE table_name 
ADD column_name datatype

or

ALTER TABLE table_name 


DROP COLUMN column_name
AS (alias) SELECT column_name AS column_alias
FROM table_name

or
SELECT column_name
FROM table_name  AS table_alias
BETWEEN SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
CREATE DATABASE CREATE DATABASE database_name
CREATE TABLE CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name2 data_type,
...
)
CREATE INDEX CREATE INDEX index_name
ON table_name (column_name)

or

CREATE UNIQUE INDEX index_name


ON table_name (column_name)
CREATE VIEW CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
DELETE DELETE FROM table_name
WHERE some_column=some_value

or

DELETE FROM table_name 


(Note: Deletes the entire table!!)

DELETE * FROM table_name 


(Note: Deletes the entire table!!)
DROP DATABASE DROP DATABASE database_name
DROP INDEX DROP INDEX table_name.index_name (SQL Server)
DROP INDEX index_name ON table_name (MS Access)
DROP INDEX index_name (DB2/Oracle)
ALTER TABLE table_name
DROP INDEX index_name (MySQL)
DROP TABLE DROP TABLE table_name
GROUP BY SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
IN SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)
INSERT INTO INSERT INTO table_name
VALUES (value1, value2, value3,....)

or

INSERT INTO table_name


(column1, column2, column3,...)
VALUES (value1, value2, value3,....)
INNER JOIN SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2 
ON table_name1.column_name=table_name2.column_name
LEFT JOIN SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2 
ON table_name1.column_name=table_name2.column_name
RIGHT JOIN SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2 
ON table_name1.column_name=table_name2.column_name
FULL JOIN SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2 
ON table_name1.column_name=table_name2.column_name
LIKE SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
ORDER BY SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC|DESC]
SELECT SELECT column_name(s)
FROM table_name
SELECT * SELECT *
FROM table_name
SELECT DISTINCT SELECT DISTINCT column_name(s)
FROM table_name
SELECT INTO SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_table_name

or

SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name
SELECT TOP SELECT TOP number|percent column_name(s)
FROM table_name
TRUNCATE TABLE TRUNCATE TABLE table_name
UNION SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
UNION ALL SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
UPDATE UPDATE table_name
SET column1=value, column2=value,...
WHERE some_column=some_value
WHERE SELECT column_name(s)
FROM table_name
WHERE column_name operator value

You might also like