Anda di halaman 1dari 16

JIMMA UNIVERSITY INSTITUTE OF TECHNOLOGY

BASIC SQL MANUAL ON SQL FOR POWER AND CONTROL ENGINEERING STUDENTS

Addishiwot T.

BASIC SQL

Chapter contents: The Basic Select Statement Selective Querying Using a Basic WHERE Clause Using Operators and Expressions Ordering Results Grouping Data SELECT Clause Techniques Sub Queries Querying from More Than One Data Source Data Source Advanced Lets use the tables we used while we were studying MYSQL. these are the table we will use till the end of this topic. Table 1 Sales representative table

SID S001 S002 S003 S004 S005 S006

First name ayele Melat Asaminew Ayele Falmata Eden

Surname dejene Alemu Guta Girma Guta Ataklti

Sex M F M M M F

Commission 10 15 10 18 16 20

Table 2 Customer Table

CID C001 C002 C003 C004 C005 C006

First_name Thomas Tigist Kebede Medhanit Mohammed Habtamu


Table 3 Sales table

surname Tadesse Demissew Tola Awoke kedir Gizaw

Sex M F M F M M

code 1 2 3 4 5 6

SID S001 S004 S002 S001 S003 S001

CID C001 C003 C003 C004 C001 C002

value 2000 250 500 450 3800 500

1.1. THE BASICS

Create the database named Sales_mangement. Use the CREATE DATABASE command statement as follows CREATE DATABASE SalesMgmt;

Now you must use this database so that you can go to the next level. i.e creating tables and populating them. use the following command USE salesMgmt; Now let us create our tables. As you all know creating table involves naming each attributes of the columns followed by their definition. Let us create each of the above tables.Use CREATE TABLE table_name(column1 data_type constraint,column2 data_type constraint,.) Type the following command and click on execute tab. CREATE TABLE sales_rep(SID char(4) NOT NULL PRIMARY KEY, First_name varchar(15) NOT NULL, Surname varchar(15) not null, Sex char(4), commission int ); Now you are in a position to populate your table.

Use INSERT statement as follows and click the execute button INSERT INSERT INSERT INSERT INSERT INTO INTO INTO INTO INTO sales_rep sales_rep sales_rep sales_rep sales_rep VALUES('S001','Ayele','Dejene','M',10); VALUES('S002','Melat','Alemu','F',15); VALUES('S003','Asaminew','Guta','M',10); VALUES('S004','Ayele','Girma','M',18); VALUES('S005','Eden','Ataklti','M',20);

Likewise we can create and populate customer and sales tables. Go ahead do the same thing for the other two tables create table customer(CID char(4) NOT NULL primary key, First_name varchar(16) NOT NULL, surname varchar(16) NOT NULL, sex char not null); To fill the table which we just created, we will use insert statement as usual INSERT INSERT INSERT INSERT INSERT INSERT INTO INTO INTO INTO INTO INTO customer customer customer customer customer customer values('C001','Thomas','Tadesse','M'); values('C002','Tigist','Demissew','F'); values('C003','Kebede','Tola','M'); values('C004','Medhanit','Awoke','M'); values('C005','Mohammed','Kedir','M'); values('C006','Habtamu','Gizaw','M');

Now it is time to create the sales table CREATE TABLE sales(code int NOT NULL primary key, SID char(4) NOT NULL, CId char(4) NOT NULL, Value int); Once again,lets populate sales table with its respected values INSERT INSERT INSERT INSERT INSERT INSERT INTO INTO INTO INTO INTO INTO sales sales sales sales sales sales values(1,'S001','C001',2000); values(2,'S004','C003',250); values(3,'S002','C003',500); values(4,'S001','C004',450); values(5,'S003','C001',3800); values(6,'S002','C002',500);

Dont you want to see the tables you created so far? Let us see them one by one

SELECTING EVERY COLUMN FOR EVERY ROW SELECT * FROM sales_rep;

SELECT * FROM customer;

SELECT * FROM sales;

The above Queries can also be written by assigning the table name to a preferred name of your choice. Lets have a closer look at of the following commands select * from sales_rep S; this means nothing but you assinged your onbject(table) name to a new table name called S.this only works only in the current querry. Later on the table is not recognized by its new name For the customer table select * from customer c;

1.2. THE BASIC SELECT STATEMENT The SELECT command allows you to retrieve data from a SQL Server database. The basic syntax is: SELECT select_list FROM table_list The select_list argument shows the list of columns that you wish to return in the results of the query. The table_list arguments are the actual tables or views that the data will be retrieved from. SELECTING SPECIFIC COLUMNS FOR EVERY ROW. Remember that the * means every column. Replacing the * by list of column names,one can select specific number of columns from the table. Lets execute the following SQL commands SELECT SID,first_name,surname FROM sales_rep;

Alternatively you can do it by naming the table to a preferred name select S.SID,S.first_name,S.surname from sales_rep S

Selective Querying Using a Basic WHERE Clause In a SELECT query, the WHERE clause is used to restrict rows returned in the query result set. The simplified syntax for including the WHERE clause is as follows: SELECT select_list FROM table_list WHERE search_conditions Lets try to work on some examples. You may well try the following queries: #1 Retrieve the data from sales representative whose ID is S004

# 2.Retrieve data for sales men whose first name is Ayele from sales representative object(table) select * from sales_rep where First_name='ayele';

# 3 Retrieve the names of persons whose commission from the company is greater than 15. select * from sales_rep where commission>15;

Likewise we can do it by renaming the table as a new name select S.SID,S.first_name,S.surname from sales_rep S where commission>15

COMBINING SEARCH CONDITIONS You can Connect multiple search conditions by using the AND, OR, and NOT logical operators. SELECT SID, First_Name, Surname FROM Sales_rep WHERE First_name = 'melat ' AND surname=alemu SELECT SID,First_Name, Surname FROM Sales_rep WHERE First_name = 'melat' AND surname='alemu';

This query returns the following results:

Likewise you can use OR to combine conditions. an OR operator is used for the two search conditions instead of an AND, meaning that if either search condition evaluates to TRUE for a row, that row will be returned:

SELECT * FROM Sales_rep WHERE First_name = 'ayele' OR This query returns the following results:

commission>14;

NEGATING A SEARCH CONDITION The NOT logical operator, unlike AND and OR, isnt used to combine search conditions, but instead is used to negate the expression that follows it. SELECT * FROM Sales_rep WHERE NOT First_name= 'ayele';

NOTE: You can use multiple operators (AND, OR, NOT) in a single WHERE clause, but it is important to keep your intentions clear by properly embedding your ANDs and ORs in parentheses. When multiple operators are used in the same WHERE clause, operator precedence is used.

SELECT * FROM Sales_rep WHERE First_name= 'ayele' AND

(surname='Dejene' OR commission>14);

USING OPERATORS AND EXPRESSIONS An expression is a combination of values, identifiers, and operators evaluated by SQL Server in order to return a result.

Using BETWEEN for Range Searches Suppose you want to retrieve information where commission payment to sales men is between 15 and 30 Select * from sales_rep where commission between 15 and 30;

USING COMPARISONS These next examples demonstrates the < and > (Less Than and greater than) operators which is used in this query to only show some intervals Select * from sales_rep where commission >15;

Select * from sales_rep where commission <15;

You can also specify an interval which has both upper bound and lower bound using greater than and less than operators.in this scenario < and > operators do the job of connector BETWEEN. Select * from sales_rep where commission >=15 AND commission<30;

The above query can be done using BETWEEN as Select * from sales_rep where commission Between 15 AND 30;

Checking for NULL Values A NULL value does not mean that the value is blank or zeroonly that the value is unknown. Lets add one more row on sales_rep table whose commission values is NULL

Insert into sales_rep(SID,First_name,surname,sex) values ('S006','Efrem','Tamiru','M') Now lets see what the table looks like Select * from sales_rep;

Run this query and see the magic Select * from sales_rep where commission is null

RETURNING ROWS BASED ON A LIST OF VALUES The IN operator is used to compare a single value from a list of values. for example select * from sales_rep where surname in ('Dejene','Girma','Tamiru');

Pattern Matching: LIKE and %


Let's look at some more additions to the SELECT statement. What if you want to return the details for Melat Alemu? Simple, you sayyou'd use the following query: SELECT * FROM sales_rep WHERE First_name='Melat' and surname='Alemu'; But what if you've forgotten how to spell Melat? Was it Mellat or maybe Milat? You may have to try a number of queries before you succeed, and if you don't happen to remember the exact spelling you will never succeed. You may want to try just using Mike, but remember that many databases consist of hundreds of thousands of records. Luckily, there is a better way. SQL allows the LIKE statement. If you remember the surname begins with Ale, you can use the following:SELECT * FROM sales_rep WHERE surname LIKE 'Ale%';

NOTE:
% is a wildcard, similar to *, but specifically for use inside a SELECT condition. It means 0 or more characters. So all of the earlier permutations on the spelling you were considering would have been returned. You can use the wildcard any number of times, which allows queries such as this: SELECT * FROM sales_rep WHERE surname LIKE '%e%';

This returns all the records, as it looks for any surname with an e in it. This is different from the following query, which only looks for surnames that start with an e:
SELECT * FROM sales_rep WHERE surname LIKE 'e%';

You could also use a query such as the following, which searches for surnames that have an e anywhere in the name and then end with an e:
SELECT * FROM sales_rep WHERE surname LIKE '%e%e';

ORDERING RESULTS The ORDER BY clause orders the results of a query based on designated columns or expressions

Sorting
Another useful and commonly used clause allows sorting of the results. An alphabetical list of employees would be useful, and you can use the ORDER BY clause to help you generate it: for instance,run the following query SELECT * FROM sales_rep ORDER BY First_name;

You may have noticed that this list is not quite correct if you want to sort by name because Ayele Dejene appears before Ayele Girma. To correct this, you need to sort on the first name as well when the surnames are the same. To achieve this, use the following:

SELECT * FROM sales_rep ORDER BY first_name,surname;

ORDER BY must appear after the required FROM clause, as well as the optional WHERE, GROUP BY Now the order is correct. To sort in reverse order (descending order), you use the DESC keyword. The following query returns all records in order of commission earned, from high to low: SELECT * FROM sales_rep ORDER BY commission DESC;

Again, you may want to further sort the three employees earning 10-percent commission. To do so, you can use the ASC keyword. Although not strictly necessary because it is the default sort order, the keyword helps add clarity: SELECT * FROM sales_rep ORDER BY commission DESC, surname ASC,first_name ASC;

Limiting the Number of Results


So far you have always gotten the full number of results that satisfy the condition returned to you. In a real-world database, however, there may be many thousands of records, and you do not want to see them all at once Using the TOP Keyword with Ordered Results The TOP keyword allows you to return the first n number of rows from a query based on the number of rows or percentage of rows that you define. In this example, the top ten rows are retrieved from For example the following query returns the 3 highest commissions from sales_rep table

select top 3 * from sales_rep order by commission desc

GROUPING DATA The GROUP BY clause is used in a SELECT query to determine the groups that rows should be put in. The simplified syntax is as follows: SELECT select_list FROM table_list [WHERE search_conditions] [GROUP BY group_by_list] GROUP BY follows the optional WHERE clause, and is most often used when aggregate functions are referenced in the select statement Lets use the sales table to show up how to use ORDER BY statement select * from sales;

select SId,sum(value) from sales group by sid;

If you want to display the maximum value for each sale,you can do it as follows select SId,max(value) from sales group by sid;

What if you want the average sell for each sales representative? select SId,avg(value) from sales group by sid;

Returning Distinct Records Sometimes, you don't want to return duplicate results. Take a look at the following query
SELECT First_name FROM sales_rep ORDER BY First_name;

As you may notice the name Ayele is repeated. But you want to know distinct names in the First_name field. Go ahead and use the word DISTINCT as follows SELECT DISTINCT First_name FROM sales_rep ORDER BY First_name; The result looks like

Counting Sometimes, all you really want to return is the number of results, not the contents of the records themselves. In this case, you'd use the COUNT() function:
SELECT COUNT(Distinct first_name) FROM sales_rep;

For column computations or aggregate functions, you can use a column alias to explicitly name the columns of your query output. You can also use column aliases to rename columns that already have a name, which helps obscure

the underlying column from the calling application (allowing you to swap out underlying columns without changing the derived column name). You can designate a column alias by using the AS keyword, or by simply following the column or expression with the column alias name. This example demonstrates producing column aliases using two different techniques: select commission as BONUS from sales_rep;

More advanced column designation Select SID,avg(Distinct commission) as average_bonus,max(commission) as max_bonus from sales_rep group by SID;

SubQueries A sub query is a SELECT query that is nested within another SELECT, INSERT, UPDATE, or DELETE statement. A sub query can also be nested inside another subquery. Sub queries can often be rewritten into regular JOINs, however sometimes an existence subquery (demonstrated in this SQL) can perform better than equivalent non-subquery methods. A correlated subquery is a subquery whose results depend on the values of the outer query. Using Sub queries to Check for the Existence of Matches This first example demonstrates checking for the existence of matching records with in a correlated sub query select * from sales_rep s where exists(select ss.sid from sales ss,sales_rep s where SS.SID=S.SID and ss.[value]>2000)

Anda mungkin juga menyukai