4. Introduction to SQL
Working through an example:
To start MYSQL in Coursera labs go to the prompt and type mysql. You only need this if you’re using Coursera labs!
1. To check the state of the databases you have created:
SHOW DATABASES;
2. To create a new database called “Degree”
CREATE DATABASE Degree;
3. To use (go inside) this database
USE Degree;
4. To create a table inside Degree;
CREATE TABLE Lecturers ( Name VARCHAR(255), DateOfBirth DATE, DateJoined DATE, PRIMARY KEY (Name, DateOfBirth) );
Note – it’s possible that Name/DOB are not unique; the lecturer acknowledged this but used it anyway.
5. We can now show our tables:
SHOW TABLES;
6. and see it in more detail like this:
DESCRIBE Lecturers;
Note we get this returned:
+-------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+-------+ | Name | varchar(255) | NO | PRI | NULL | | | DateOfBirth | date | NO | PRI | NULL | | | DateJoined | date | YES | | NULL | | +-------------+--------------+------+-----+---------+-------+
A Primary Key cannot be Null, but unless we specify otherwise a field could have a null value.
7. We can now insert a value
INSERT INTO Lecturers VALUES ('David Lewis', '1955-10-09', '1985-03-05');
8. If we now want to select all names from Lecturers:
SELECT Name FROM Lecturers;
This returns a table showing one record – David Lewis.
9. To see all fields from the table:
SELECT * FROM Lecturers;
10. We can add a constraint to a query:
SELECT Name FROM Lecturers WHERE DateJoined > '2000-01-01';
Tuesday 26 October 2021, 564 views
Next post: 5. Joins in SQL Previous post: 3. Relational Databases
Databases and Advanced Data Techniques index
- 26. A very good guide to linked data
- 25. Information Retrieval
- 24. Triplestores and SPARQL
- 23. Ontologies – RDF Schema and OWL
- 22. RDF – Remote Description Framework
- 21. Linked Data – an introduction
- 20. Transforming XML databases
- 19. Semantic databases
- 18. Document databases and MongoDB
- 17. Key/Value databases and MapReduce
- 16. Distributed databases and alternative database models
- 15. Query efficiency and denormalisation
- 14. Connecting to SQL in other JS and PHP
- 13. Grouping data in SQL
- 12. SQL refresher
- 11. Malice and accidental damage
- 10. ACID: Guaranteeing a DBMS against errors
- 9. Normalization example
- 8. Database normalization
- 7. Data integrity and security
- 6. Database integrity
- 5. Joins in SQL
- 4. Introduction to SQL
- 3. Relational Databases
- 2. What shape is your data?
- 1. Sources of data
Leave a Reply