Database Access using SQL Very basic introduction James
Database Access using SQL Very basic introduction James Brucker
Database Management System SELECT * FROM city WHERE name LIKE Ban% User Interface & communications protocol Database Manager controls access to the database & provides: • authentication • enforce permissions • data integrity • access services Database: a structured, self-describing collection of data.
Client - Server Structure n n n The database server is a separate process running on a host. The database client can be on a different machine. Many programs may be client using standard API. client using "mysql" utility client using Java+JDBC client using Excel mysqld (server)
Exercise n n n Use the "mysql" command n if machine doesn't have "mysql" then use My. SQL Query Browser GUI. What is the version number? Look at help message: how do you connect to server? dos> mysql --version mysql Ver 14. 12 Distrib 5. 0. 16, for Win 32 dos> mysql --help displays a long help message: very useful
Exercise n Connect to My. SQL server on host "se. cpe. ku. ac. th". n n user: student password: student What My. SQL version is the server running? dos> mysql -h se. cpe. ku. ac. th -u student -p Enter password: student mysql> SELECT version(); mysql>
Structure of a Database n n A database system may contain many databases. Each database is composed of schema and tables. sql> SHOW databases; +-------+ | Database | +-------+ | mysql | | test | | bank | | world | +-------+ My. SQL only shows databases that a user has permission to access. sql> USE bank; sql> SHOW tables; +--------+ | Tables_in_bank | +--------+ | accounts | | clients | +--------+
Structured Query Language n n The standard language for manipulating a database is Structured Query Language (SQL). SQL is case-insensitive and free format. Commands are entered interactively or in a script file. SQL statements can span multiple lines: n end a statement with a semi-colon ; sql> USE Bank; database changed. SQL statements end with a semi-colon. sql> SHOW tables; sql> SHOW columns FROM accounts; sql> SELECT account. Number, account. Name, client. ID, balance FROM accounts;
A Simple Database Structure SQL commands to show the structure of Bank database sql> SHOW tables; +--------+ | Tables_in_bank | +--------+ | accounts | | clients | +--------+ SQL statements must end with a semi-colon. If you omit semi-colon, SQL will prompt for more input. sql> SHOW columns FROM accounts; +---------+-------+-----+-----+-------+ | Field | Type | Null | Key | Default | Extra | +---------+-------+-----+-----+-------+ | account. Number | varchar(8) | | | account. Name | varchar(40) | | | client. ID | int(11) | | MUL | 0 | | | balance | double | | | 0 | | | available. Balance | double | | | 0 | | +---------+-------+-----+-----+-------+
Exercise n Connect to My. SQL server on host "se. cpe. ku. ac. th". n user: student password: student n What databases are there? n What tables are in the world database? dos> mysql -h se. cpe. ku. ac. th -u student -p Enter password: student mysql> SHOW databases; mysql> SHOW tables from world; mysql> USE world; mysql> SHOW tables;
Exercise n Omit the semi-colon. What happens? mysql> SHOW tables No semi-colon. n Enter a command on several lines mysql> SHOW tables from world ;
Structure of a Database Table n n n A table contains records (rows) of data. A record is composed of several columns (fields). A database schema can contain index files, views, and other information in addition to tables. sql> SELECT * FROM Accounts; +---------------+-----+-----+ | account. Number | account. Name | client. ID | balance | +---------------+-----+-----+ | 1111 | J. Brucker | 1111 | 35000 | | 11111112 | Vacation Fund | 1111 | 22500 | | 11111113 | P. Watanapong | 11111120 | 300000 | | 11111114 | CPE Fund | 11111120 | 1840000 | +---------------+-----+-----+
DESCRIBE n DESCRIBE also shows a description of a table. n output is same as "SHOW COLUMNS FROM. . . ". sql> DESCRIBE accounts; +---------+-------+-----+-----+-------+ | Field | Type | Null | Key | Default | Extra | +---------+-------+-----+-----+-------+ | account. Number | varchar(8) | | | account. Name | varchar(40) | | | client. ID | int(11) | | MUL | 0 | | | balance | double | | | 0 | | | available. Balance | double | | | 0 | | +---------+-------+-----+-----+-------+
Exercise: For the world database: n what columns does each table have? n what information do you suppose is in the columns? n What are the names of some data types in SQL? mysql> describe city; +-------+-----+------+-----+------+ | Field | Type | Null | Key | Default | Extra | +-------+-----+------+-----+------+ | ID | int(11) | NO | PRI | NULL | auto_incr | | Name | char(35) | NO | | | Country. Code | char(3) | NO | | | District | char(20) | NO | | | Population | int(11) | NO | | 0 | | +-------+-----+------+-----+------+
Exercise: O-O Analogy of a Table? Database Object Oriented table _________ record (row) _________ fields (columns) _________ sql> SELECT * FROM Accounts; +---------------+-----+-----+ | account. Number | account. Name | client. ID | balance | +---------------+-----+-----+ | 1111 | J. Brucker | 1111 | 35000 | | 11111112 | Vacation Fund | 1111 | 22500 | | 11111113 | P. Watanapong | 11111120 | 300000 | | 11111114 | CPE Fund | 11111120 | 1840000 | +---------------+-----+-----+
Qualifying Names n SQL uses ". " to qualify elements of a hierarchy n just like most O-O languages Bank. accounts" table in Bank db accounts. balance field in accounts Bank. accounts. balance sql> DESCRIBE bank. accounts; +---------+-------+-----+-----+-------+ | Field | Type | Null | Key | Default | Extra | +---------+-------+-----+-----+-------+ | account. Number | varchar(8) | | | account. Name | varchar(40) | | | client. ID | int(11) | | MUL | 0 | | | balance | double | | | 0 | | | available. Balance | double | | | 0 | | +---------+-------+-----+-----+-------+
Diagram of Database Structure Database Catalog Schema Table Table field 1: t 1 field 2: t 2 field 3: t 3 field 1: t 1 field 2: t 2 field 3: t 3 indexes indexes In My. SQL the words "database" and "schema" are used inconsistently.
Database Operations n Operations you can perform on a database include: USE choose a database SELECT query (search) the data INSERT add new records to a table(s) UPDATE modify information in existing records DELETE delete records from a table sql> USE bank; sql> SELECT * FROM clients WHERE firstname = 'james'; | client. ID | first. Name | last. Name | email | +----------+----------------+ | 1111 | James | Brucker | jbrucker@yahoo. com | sql> UPDATE accounts SET balance=100000 WHERE client. ID='1111'; Query OK, 1 row affected (0. 09 sec)
SQL SELECT statement n Select columns from a table and display them: SELECT n field 1, field 2, field 3 FROM tablename ; This displays ALL rows from the table. sql> SELECT * from accounts; +---------------+-----+-----+ | account. Number | account. Name | client. ID | balance | +---------------+-----+-----+ | 1111 | J. Brucker | 1111 | 35000 | | 11111112 | Vacation Fund | 1111 | 22500 | | 11111113 | P. Watanapong | 11111120 | 300000 | | 11111114 | CPE Fund | 11111120 | 1840000 | +---------------+-----+-----+
Qualifying SELECT n Select columns from a table that match some criteria: SELECT field 1, field 2, field 3 FROM table WHERE condition ORDER BY field 1, . . . [ASC|DESC]; sql> SELECT account. Number, . . . FROM accounts WHERE balance > 100000 ORDER by balance DESC; +---------------+-----+-----+ | account. Number | account. Name | client. ID | balance | +---------------+-----+-----+ | 11111114 | CPE Fund | 11111120 | 1840000 | | 11111113 | P. Watanapong | 11111120 | 300000 | +---------------+-----+-----+ SQL statements and field names are case insensitive, but the field values may not be! It depends on the data type of the field.
Counting with SELECT n Select can be used with functions, such as COUNT: SELECT COUNT(*) from Accounts WHERE condition; sql> SELECT count(*) from accounts; +-----+ | count(*) | +-----+ | 4 | +-----+ sql> SELECT count(*) from accounts WHERE balance > 100000;
Exercise: Use the world database to answer these questions: n How many countries and cities are in the database? n What is the country code for China? n use the condition WHERE name = 'China' n How many cities are in China? n What languages are spoken in China? n n what is the official language? List the cities in China, sorted by population (largest to smallest). Use "ORDER BY. . . "
Exercise: n What is the country code for Thailand? n What is the population of Thailand? n How many cities are in Thailand? n n what are the names of the cities? What languages are used in Thailand?
Strings and wildcards in SELECT n Use single quote marks for String data. n For exact matches use field = 'value' SELECT * FROM city WHERE Country. Code = 'THA'; n For pattern matches, use: field LIKE 'pattern' SELECT * FROM city WHERE name LIKE 'Ba%'; n In SQL, '%' means "match anything". SELECT * FROM clients WHERE first. Name LIKE 'J%' ORDER BY last. Name; SQL statements and field names are case insensitive, but the field values may not be! It depends on the data type of the field.
Logical operations n OR SELECT * FROM City WHERE District='Songkhla' OR District='Bangkok'; n AND SELECT Name, Surface. Area FROM Country WHERE Continent = 'Africa' AND Surface. Area > 1000000; n NOT SELECT * FROM Accounts WHERE NOT Available. Balance = 0;
Set operations n IN SELECT * FROM City WHERE District IN ('Songkhla', 'Bangkok');
Exercise: who lives longest? n How many countries are in Asia? n In which countries in Asia do people live longest? n List the countries sorted by life expectancy. n Where can you expect to live > 80 years? n What country in Asia has the shortest life expectancy? n How does Thailand rank for life expectancy? n n COUNT the countries in Asia with life expectancy less than in Thailand. COUNT the countries in Asia with life expectancy greater than in Thailand.
Exercise n Find all cities in Thailand, ranked by Population n n use: "SELECT. . . ORDER BY Population DESC" do you see any errors in the data?
Using Functions in SELECT n How many people are in the world? SELECT SUM(population) FROM Country; n What is the largest surface area of any country? SELECT MAX(Surface. Area) FROM Country; n How many cities are from Thailand? SELECT COUNT(*) FROM City WHERE countrycode = 'THA'; n What is the version of My. SQL? SELECT version();
Exercise n What is the total population of the world? n What is the total population of Asia? n What is the average and maximum population per sq. km. of the countries in the world? n Country. Surface. Area is the area in sq. km.
Getting Help Built-in help for n how to use the mysql command n SQL statements mysql> HELP SELECT If mysql doesn't have help on SQL commands, then load the "help tables" data onto the server. Download help table data from: http: //dev. mysql. com/downloads in the "Documentation" section.
Using Subqueries n Use the result of one query as part of another query. n Which account has the greatest balance? SELECT Account. Number, Account. Name FROM Accounts WHERE balance = ( SELECT max(balance) FROM Accounts ); n Where do people live the longest? SELECT Name, Life. Expectancy FROM Country WHERE Life. Expectancy = ( SELECT max(Life. Expectancy) FROM Country ); To use SQL subqueries in My. SQL you need version 4. 1 or newer.
Exercise n Where do people live longer than in Thailand? n ORDER the results by DESCending life expectancy. SELECT Name, Life. Expectancy FROM Country WHERE Life. Expectancy > ( insert subquery here ) ORDER BY. . . ;
Exercise n Which nation is the most crowded? n n n Find the country with maximum population density (population per sq. km. ) Show the name and the population density Hint: create an alias for a computed field: sql> SELECT name, population/surface. Area AS density WHERE. . . Alias: density : = population/surface. Area
Exercise n Is Thailand more crowded than neighbor countries? n n List the name and population density of all countries in the same region as Thailand. use a subquery for "same region as Thailand": SELECT. . . FROM Country WHERE Region = (SELECT Region. . . Code=. . . ) ORDER. . . ; n Order the results by population density.
Exercise n How does Thailand's economic output per capita compare with other countries in Asia? n Compare 1, 000 * GNP / population.
Modify data with UPDATE n UPDATE changes data in one or more tables: UPDATE accounts SET balance=100000 WHERE client. ID='1111'; sql> UPDATE accounts SET balance=100000 WHERE client. ID='1111'; +---------------+-----+-----+ | account. Number | account. Name | client. ID | balance | +---------------+-----+-----+ | 1111 | J. Brucker | 1111 | 1000000 | | 11111112 | Vacation Fund | 1111 | 1000000 | | 11111113 | P. Watanapong | 11111120 | 300000 | | 11111114 | CPE Fund | 11111120 | 1840000 | +---------------+-----+-----+
UPDATE statement n you can change multiple columns: UPDATE table SET field 1=value 1, field 2=value 2 WHERE condition; sql> UPDATE clients SET email='jb@yahoo. com', first. Name='Jim' WHERE client. ID='1111'; Query OK, 1 row affected (0. 09 sec) | client. ID | first. Name | last. Name | email | +----------+----------------+ | 1111 | Jim | Brucker | jb@yahoo. com |
Warning: UPDATE is immediate! n n There is no "undo". Changes take effect immediately. Be Careful! If you forget the WHERE clause it will change all the rows in the table! sql> UPDATE accounts SET balance=100000 ; /* oops! */ +---------------+-----+-----+ | account. Number | account. Name | client. ID | balance | +---------------+-----+-----+ | 1111 | J. Brucker | 1111 | 1000000 | | 11111112 | Vacation Fund | 1111 | 1000000 | | 11111113 | P. Watanapong | 11111120 | 1000000 | | 11111114 | CPE Fund | 11111120 | 1000000 | +---------------+-----+-----+
Exercise n Get the current population for a city in Thailand. n n Search the web or www. ttt. go. th Update the population in the world database. Question: what happens if two people change the same city data (same record) at the same time?
Inserting new records n INSERT adds a new record to a table INSERT INTO tablename VALUES ( value 1, value 2, . . . ); sql> INSERT INTO Accounts VALUES ('2222', 'Ample Rich', '0000' 10000000); Query OK, 1 row affected. +---------------+-----+-----+ | account. Number | account. Name | client. ID | balance | +---------------+-----+-----+ | 2222 | Ample Rich | 0000 |10000000 | +---------------+-----+-----+
Insert into columns by name You can specify which columns will receive the values: INSERT INTO tablename (field 1, field 2, . . . ) VALUES ( data 1, data 2, . . . ); sql> INSERT INTO Accounts (account. Number, balance, account. Name) VALUES ('2222', 10000000, 'Ample Rich'); Query OK, 1 row affected. +---------------+-----+-----+ | account. Number | account. Name | client. ID | balance | +---------------+-----+-----+ | 20000000 | Ample Rich | |10000000 | +---------------+-----+-----+
Exercise n Add your home town to the City table n or, add another City to the City table. sql> INSERT INTO city (name, country. Code, district, population) VALUES ('Bangsaen', 'THA', 'Chonburi', 100000); Query OK, 1 row affected. The ID field has a qualifier of "AUTO_INCREMENT". (use "DESCRIBE City") This means My. SQL will assign the ID value itself.
Exercise n n View the city data that you just added! Use UPDATE to change the population of the city you added. sql> UPDATE City SET population = 95000 WHERE city. name = 'Bangsaen'; Query OK, 1 row affected. sql> SELECT * FROM City WHERE City. name = 'Bangsaen';
How do you get data into a table? n n n Use INSERT commands (boring). Put INSERT commands in a Script (text file) and "source" the file (better). Import command (may depend on DBMS): n LOAD DATA INFILE 'filename' INTO table. . . n BCP ("bulk copy" - MS SQL server)
Copying Data Between Tables n Suppose we have another table named New. Accts n New. Accts has account. Number, account. Name, . . . INSERT INTO tablename (field 1, field 2, . . . ) SELECT field 1, field 2, field 3 FROM othertable WHERE condition; sql> INSERT INTO Accounts SELECT * FROM New. Accts WHERE account. Number NOT NULL;
Relating Tables n n n The power of a relational database is the ability to selectively combine data from tables. You can use: select data from multiple tables by matching a field relations can be n 1 -to-1 student -> photograph n 1 -to-many country -> city n many-to-1 city -> country n many-to-many language -> country
Relational Structure The Bank. clients table contains bank client information. The primary key is client. ID. sql> DESCRIBE clients; +-------------+-----+-----+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+-----+-----+-------+ | client. ID | int(11) | | PRI | 0 | | | first. Name | varchar(40) | | | last. Name | varchar(40) | | | email | varchar(40) | YES | | NULL | | +-------------+-----+-----+-------+ Accounts account. Number account. Name client. ID balance available. Balance client. ID Clients client. ID (KEY) first. Name last. Name email
Joining Tables n n The power of a database comes from the ability to relate or "join" tables using a condition. Use "table. field" to qualify a field name: Accounts. balance, Clients. client. ID, n . . . The client. ID joins the Accounts table and Clients table. Accounts account. Number account. Name client. ID balance available. Balance * 1 Clients client. ID (KEY) first. Name last. Name email Accounts. client. ID = Clients. client. ID
Joining Tables (2) n Show the balance of all accounts owned by J. Brucker. n the account balance is in the Accounts table. n the client name is the Clients table. n relate the tables using client. ID field. SELECT account. Number, first. Name, balance FROM Accounts, Clients WHERE Accounts. client. ID = Clients. client. ID AND clients. first. Name = 'James'; +---------------+-----+ | account. Number | first. Name | balance | +---------------+-----+ | 1111 | James | 100000 | | 11111112 | James | 22500 |
Exercise n What fields can we use to relate tables in the world database? City Country Code Name Continent Region Surface. Area Population GNP Local. Name Capital ID Name Country. Code District Population Country. Language Country. Code Language is. Official Percentage
Example: Join Country and City SELECT Country. Name, City. Name FROM Country, City WHERE Country. Code = City. Country. Code AND Continent = 'South America'; Country Code Name Continent Region Surface. Area Population GNP Local. Name Capital City Country. Code = City. Country. Code ID Name Country. Code District Population
Exercise n In what countries is the Thai language used? n By what percentage of the people? Example: SELECT. . . FROM Country, Country. Language WHERE Country. Code = Country. Language. Country. Code AND. . . ;
Use Aliases to Reduce Typing n In what countries is Chinese the official language? SELECT C. name, L. language, L. percentage FROM Country C, Country. Language L WHERE C. code = L. countrycode AND language = 'Chinese' AND is. Official = 'T'; L is an alias for you can omit table name when there is no ambiguity Country. Language
Exercise n What countries use English? n n ORDER the results by percentage spoken, from largest to smallest %. In how many countries is English the official language? Harder n In the world, approximately how many people speak English? n sum( population * Language. percentage / 100 )
"JOIN" n JOIN joins tables n Many forms: n n INNER JOIN (include only matching columns) n OUTER JOIN (include all columns) n LEFT OUTER JOIN n NATURAL JOIN n CONDITION JOIN Learn them all in a course on database. . .
Example of a Condition Join n JOIN the Country. Language and Language tables using the country code: SELECT * FROM Country C JOIN Country. Language L ON C. code = L. countrycode ;
Exercise n JOIN the Country and Language tables. n View Country name and language with "SELECT. . . " n How many times is Thailand listed in the results? n How many times is China listed in the results? How can you order the results by language ?
Multiple Condition Join n You can join many tables at one time: SELECT CO. name, CI. *, L. language FROM Country CO JOIN Country. Language L ON CO. code = L. countrycode JOIN City CI ON CO. code = CI. countrycode WHERE. . . ; /* more conditions */
Data Definition Commands CREATE create a Table, Index, or Database ALTER modify structure of a Database or Table DROP delete an entire Table, Index, or Database RENAME rename a Table
Creating a Table n To add a table to a database: CREATE TABLE tablename ( field 1, field 2, . . . ) options ; sql> CREATE TABLE CUSTOMER ( account. Number VARCHAR(8) NOT NULL, client. ID VARCHAR(40) NOT NULL, balance DOUBLE DEFAULT '0', available. Balance DOUBLE DEFAULT '0' ) ; Query OK, 0 rows affected.
Productivity Hint n n Type the "CREATE TABLE" statement into a file. Read the file into mysql: source filename; File: /temp/create-table. sql CREATE TABLE CUSTOMER ( account. Number VARCHAR(8) NOT NULL, client. ID VARCHAR(40) NOT NULL, balance DOUBLE DEFAULT '0', available. Balance DOUBLE DEFAULT '0', PRIMARY KEY( client. ID ) ) ; sql> SOURCE /temp/create-table. sql; Query OK, 0 rows affected.
Deleting Records n Use DELETE to delete one or more records DELETE FROM tablename WHERE condition; n Delete all bank accounts with zero balance sql> DELETE FROM Accounts WHERE balance <= 0; Query OK, 0 row affected.
Deleting a Table n To delete a table to a database: DROP TABLE tablename ; sql> DROP TABLE CUSTOMER ;
Exercise n Delete the city you added to the City table. n On your friend's machine, is it deleted immediately?
Views n A View acts like a "virtual table" containing selected data from one or more real tables. Country Name Continent Code. . . Country. Lan guage Language Percentage is. Official. . . CREATE VIEW My. View AS. . . My. View Name Language Percentage
View Example Create a view that shows country names, languages, and percentages. sql> CREATE VIEW lang AS SELECT name, language, percentage FROM Country C, Country. Language L WHERE C. code = L. countrycode ORDER BY language ASC; Query OK, 0 rows affected. Use a view similar to using a table: sql> SELECT * FROM lang WHERE language='Thai';
Productivity Hint n n Type the "CREATE VIEW" statement into a file. Read the file into mysql: source filename; File: /temp/makeview. sql CREATE VIEW lang AS SELECT name, language, percentage FROM Country C, Country. Language L WHERE C. code = L. countrycode; sql> SOURCE /temp/makeview. sql; Query OK, 0 rows affected.
Exercise n n n Create a view that shows these fields: City. name as name Country. name as country Region Population of the city Official language id of the city Each person should use a different name for his view, to avoid interfering with each other. List the tables in world ( show tables ).
Exercise n List the cities in Southest Asia where English is the official language and population is over 100, 000.
Exercise n Ask My. SQL to "describe" your view. n Delete your view: DROP VIEW viewname ;
Review What is the command to. . . n list all the databases that you have access to? n use a database? n get information about the structure of a table? n query data in one or more tables? n add new row(s) of data to a table? n change some existing data in rows? n delete some rows of data? n delete an entire table?
SQL Quiz Database Game
Rules n "largest" and "smallest" refer to size (surface. Area). n "most populous", "least populous" refer to population n "richest", "poorest" means GNP per capita (population), not total GNP, but the GNP must not be zero (GNP = 0 means no data).
What is the World's Smallest Nation? n n How big is it? How many people live there?
What is the Largest Country in Africa? n n Show the SQL How big is it?
In what countries is Thai spoken? SELECT c. name, l. language FROM Country c JOIN Country. Language l ON c. code = l. countrycode WHERE. . .
How many nations speak English? n n Is English spoken in Thailand? Fix the database. SELECT COUNT(*) FROM Country c JOIN Country. Language l ON c. code = l. countrycode WHERE. . .
What cities have a population > 6 M ? n n Print a list of city name, population, country name sorted by population -- largest first +---------+------------------+ | name | population | country_name | +---------+------------------+. . . | Bangkok | 6320174 | Thailand |. . .
What cities are in Thailand ? n Sort them by District +-------------------+------------+ | ID | Name | District | Population | +-------------------+------------+ | 3320 | Bangkok | 6320174 |. . .
Resources My. SQL n http: //dev. mysql. com/tech-resources/articles/ Learning SQL n http: //www. w 3 schools. com/sql/ nice tutorial and command reference
- Slides: 80