Skip to content

Files

Latest commit

cf84791 · Jan 14, 2025

History

History
104 lines (89 loc) · 1.98 KB

Basic_tutorial_to_SQL.md

File metadata and controls

104 lines (89 loc) · 1.98 KB

Make a Database

show databases;
create database db_name;
use db_name;

Make a Table in the Database

show tables;
create table table_name (
    id int AUTO_INCREMENT,
    name varchar(299),
    age int
);

Inserting Data in the Table

show tables;
describe table_name;
insert into table_name values (1, "name", 25);

Pull Data from the Table

select * from table_name;
select name from table_name;
SELECT DISTINCT location FROM users; 
SELECT * FROM users WHERE dept LIKE 'd%'; 
SELECT * FROM users WHERE dept IN ('design', 'sales');
SELECT * FROM users WHERE age BETWEEN 20 AND 25;
select * from table_name where column_name = value;
select * from table_name where column_name = value or column_name = another_value;
select id from table_name where age < 30;
select * from table_name where not column_name = value;

Remove Data from the Table

delete from table_name where column_name = value;

Update Data

update table_name set column_name = new_value where column_name = value;

Sorting

select * from table_name order by column_name asc;
select * from table_name order by column_name desc;

Generate Truly Random Ages for All Rows in One Command

UPDATE your_table_name
SET age = FLOOR(RAND() * (50 - 20 + 1)) + 20
WHERE id IN (1, 2, 3, 4, 5, 6, 7);

Alter Table

alter table table_name add new_column boolean;

Alter Type

ALTER TABLE users MODIFY COLUMN age INT(3);
ALTER TABLE "table name"
CHANGE COLUMN "oldColumn" "newcolumnName" VARCHAR(255);

Deleting Data

delete from table_name where condition;
drop table table_name;
drop database db_name;

Concatenate Data

SELECT CONCAT(first_name, ' ', last_name) AS 'Name', dept FROM users;

Indexing

CREATE INDEX LIndex On users(location);
DROP INDEX LIndex ON users;

Linking tables

 PRIMARY KEY(id),
   FOREIGN KEY (user_id) REFERENCES users(id)