Vous êtes sur la page 1sur 13

PROGRAMACION MySQL

FUNCIONES MySQL
CONCAT(cad1, cad2, cad3, , cadn): Concatena cadenas dadas en los
argumentos.
CONCAT_WS(separador, cad1, cad2, cad3, ): Concatena cadenas con
separador.
CONV(n, from_base,to_base): Convierte un nmero n de base.
ELT(n, cad1, cad2, cad3,,cadn): Devuelve la cadena de posicin n.
LAST_INSERT_ID( ): Devuelve el ltimo nmero de secuencia generado.
LCASE(cadena) o LOWER(cadena): Devuelve la cadena en minscula.
UCASE(cadena) o UPPER(cadena): Devuelve la cadena en mayscula.
LEFT(cadena, n): Da los n elementos ms a la izquierda de la cadena.
RIGHT(cadena, n): Da los n elementos ms a la derecha de la cadena.
LOCATE(subcadena, cadena, n): Da la primera posicin de la subcadena a partir
de posicin n.
LENGTH(cadena): Devuelve el nmero de caracteres de la cadena.
LPAD(cadena,n,cadena1): aade cadena1 a cadena a la izquierda hasta que la
cadena tenga n caracteres.
RPAD(cadena,n,cadena1): aade cadena1 a cadena a la derecha hasta que la
cadena tenga n caracteres.
LTRIM(cadena): Devuelva la cadena despus de truncar los espacios en blanco
a la izquierda.
RTRIM(cadena): Devuelva la cadena despus de truncar los espacios en blanco
a la derecha.
MID(cadena, posicin, n): Da subcadena de longitud n a partir de posicin.
POSITION(subcadena, cadena): Da la primera posicin de la subcadena en la
cadena.
REPEAT(cadena, n): Repite la cadena n veces.
REPLACE(cad1 ,cad2, cad3): Reemplaza cad2 por cad3 en cad1.
REVERSE(cadena): Devuelve la cadena invertida.
SOUNDEX(cadena): Devuelve cadena soundex parecida a cadena dada.
SPACE(n): Devuelve cadena de espacios en blanco repetidos n veces.
SUBSTRING(cadena, n): Devuelve subcadena de cadena desde n hasta el final.
SUBSTRING(cadena, n, m): Devuelve subcadena de cadena de tamao m a
partir de n.
CONECTAR Y CREAR USUARIO DNDOLE PRIVILEGIOS
MariaDB [none]> mysql -u root -h localhost;
MariaDB [none]> update user set password= 26012010 where user=root;
MariaDB [none]> select now(), user(), versin();
MariaDB [none]> create user manuel@localhost identified by 18061962;
MariaDB [none]> grant all privileges on sampdb.* to manuel identified by
18061962;
DATABASE books
MariaDB [none]> create database books;
MariaDB [none]> use books;

MariaDB [books]> source C:/xampp/htdocs/ejemplos/9/bookorama.sql


bookorama.sql
create table customers ( customerid int unsigned not null auto_increment
primary key,
name char(50) not null, address char(100) not null, city char(30) not null );
create table orders ( orderid int unsigned not null auto_increment primary key,
customerid int unsigned not null, amount float(6,2), date date not null );
create table books ( isbn char(13) not null primary key, author char(50), title
char(100),
price float(4,2) );
create table order_items ( orderid int unsigned not null, isbn char(13) not null,
quantity tinyint unsigned, primary key (orderid, isbn) );
create table book_reviews ( isbn char(13) not null primary key, review text );
alter table order_items add foreign key (orderid) references orders (orderid);
-----------------------MariaDB [books]> show databases;
MariaDB [books]> show tables;
MariaDB [books]> describe customers;
MariaDB [books]> source C:/xampp/htdocs/ejemplos/10/book_insert.sql
book_insert.sql
insert into customers values (NULL, "Julie Smith", "25 Oak Street", "Airport
West"),
(NULL, "Alan Wong", "1/47 Haines Avenue", "Box Hill"),
(NULL, "Michelle Arthur", "357 North Road", "Yarraville");
insert into orders values (NULL, 3, 69.98, "2000-04-02"), (NULL, 1, 49.99,
"2000-04-15"),
(NULL, 2, 74.98, "2000-04-19"), (NULL, 3, 24.99, "2000-05-01");
insert into books values
("0-672-31697-8", "Michael Morgan", "Java 2 for Professional Developers",
34.99),
("0-672-31745-1", "Thomas Down", "Installing Debian GNU/Linux", 24.99),
("0-672-31509-2", "Pruitt, et al.", "Teach Yourself GIMP in 24 Hours", 24.99),
("0-672-31769-9", "Thomas Schenk", "Caldera OpenLinux System
Administration Unleashed", 49.99);
insert into order_items values (1, "0-672-31697-8", 2), (2, "0-672-31769-9", 1),
(3, "0-672-31769-9", 1), (3, "0-672-31509-2", 1), (4, "0-672-31745-1", 3);
insert into book_reviews values ("0-672-31697-8", "Morgan's book is clearly
written and goes well beyond most of the basic Java books out there.");
------------------------MariaDB [books]> load data infile C:/xampp/htdocs/ejemplos/13/customers.txt
into table customers;
MariaDB [books]> alter table customers auto_increment= 8; // para cambiar
posicin
MariaDB [books]> select table_schema, table_name, table_type, table_rows,
engine from information_schema.tables where table_schema=books;
MariaDB [books]> alter orders type= MyISAM; // para cambiar de motor
almacenamiento
MariaDB [books]> source C:/xampp/htdocs/ejemplos/13/basic_function.sql;
MariaDB [books]> source
C:/xampp/htdocs/ejemplos/13/basic_function_with_variables.sql;

MariaDB [books]> source


C:/xampp/htdocs/ejemplos/13/basic_stored_procedure.sql;
MariaDB [books]> SHOW CREATE PROCEDURE total_orders;
MariaDB [books]> call total_orders(@a); // ejecuta el procedimiento y guarda
en @a
MariaDB [books]> select @a; // muestra la salida del procedimiento
MariaDB [books]> source
C:/xampp/htdocs/ejemplos/13/contador_numeros_procedure.sql;
MariaDB [books]> CALL numeros_1_hasta_n(5);
MariaDB [books]> source C:/xampp/htdocs/ejemplos/13/control_structures_cursors.sql;
basic_function.sql
# Basic syntax to create a function
delimiter //
create function add_tax (price float) returns float
return price*1.1;
//
delimiter ;
basic_function_with_variables.sql
# Basic syntax to create a function
delimiter //
create function add_tax2 (price float) returns float
begin
declare tax float default 0.10;
return price*(1+tax);
end
//
delimiter ;
basic_stored_procedure.sql
# Basic stored procedure example
delimiter //
create procedure total_orders (out total float)
begin
select sum(amount) into total from orders;
end
//
delimiter ;
contador_numeros_procedure.sql
DELIMITER //
CREATE PROCEDURE numeros_1_hasta_n (IN n INT)
BEGIN
DECLARE contador INT DEFAULT 1;
WHILE contador<=n DO
SELECT contador;
SET contador = contador + 1 ;

END WHILE;
END
//
DELIMITER ;
control_structures_cursors.sql
# Procedure to find the orderid with the largest amount
# could be done with max, but just to illustrate stored procedure principles
delimiter //
create procedure largest_order(out largest_id int)
begin
declare this_id int;
declare this_amount float;
declare l_amount float default 0.0;
declare l_id int;
declare done int default 0;
declare continue handler for sqlstate '02000' set done = 1;
declare c1 cursor for select orderid, amount from orders;
open c1;
repeat
fetch c1 into this_id, this_amount;
if not done then
if this_amount > l_amount then
set l_amount=this_amount;
set l_id=this_id;
end if;
end if;
until done end repeat;
close c1;
set largest_id=l_id;
end
//
delimiter;
MariaDB [books]> SHOW columns FROM information_schema.routines;
MariaDB [books]> SELECT * FROM INFORMATION_SCHEMA.ROUTINES;
Estas dos sentencias SELECT devuelven lo mismo:
MariaDB [books]> SELECT routine_definition FROM
information_schema.routines WHERE routine_name = add_tax2;
MariaDB [books]> SELECT routine_definition FROM
information_schema.routines WHERE specific_name = add_tax2;

DATABASE sampdb
MariaDB [none]> create database sampdb;
MariaDB [none]> use sampdb;
MariaDB [sampdb]>
source C:/Users/Manuel Montiel/Documents/MySQL/sampdb/crear_tablas.sql;

crear_tablas.sql
CREATE TABLE president ( last_name VARCHAR(15) NOT NULL,
first_name VARCHAR(15) NOT NULL, suffix VARCHAR(5) NULL, city
VARCHAR(20) NOT NULL,
state VARCHAR(2) NOT NULL, birth DATE NOT NULL, death DATE NULL );
CREATE TABLE member ( member_id INT UNSIGNED NOT NULL
AUTO_INCREMENT,
PRIMARY KEY (member_id), last_name VARCHAR(20) NOT NULL, first_name
VARCHAR(20) NOT
NULL, suffix VARCHAR(5) NULL, expiration DATE NULL DEFAULT '0000-00-00',
email VARCHAR(100) NULL, street VARCHAR(50) NULL, city VARCHAR(50)
NULL,
state VARCHAR(2) NULL, zip VARCHAR(10) NULL, phone VARCHAR(20) NULL,
interests VARCHAR(255) NULL );
MariaDB [sampdb]>
SOURCE C:/Users/Manuel
Montiel/Documents/MySQL/sampdb/crear_tabla_student.sql;
MariaDB [sampdb]> LOAD DATA INFILE
C:/Users/Manuel Montiel/Documents/MySQL/sampdb/students.txt INTO TABLE
student;
MariaDB [sampdb]> UPDATE student SET sex=M WHERE student_id=2;
MariaDB [sampdb]> INSERT INTO grade_event (date, category) VALUES (200409-03,Q);
LOAD DATA INFILE
C:/Users/Manuel Montiel/Documents/MySQL/sampdb/presidentes.txt INTO
TABLE president;

DATABASE educa
MariaDB [none]> CREATE DATABASE educa;
MariaDB [none]> USE educa;
MariaDB [educa]>
SOURCE C:/Users/Manuel
Montiel/Documents/MySQL/educa/crear_tablas_educa.sql;
MariaDB [educa]> SHOW CREATE TABLE estudiante; // para ver estructura
tabla
MariaDB [educa]> ALTER TABLE estudiante DROP FOREIGN KEY
estudiante_ibfk_1;
MariaDB [educa]> ALTER TABLE estudiante CHANGE esp esp CHAR(4);
MariaDB [educa]> ALTER TABLE estudiante ADD FOREIGN KEY (esp)
REFERENCES departamento (dept);
MariaDB [educa]> LOAD DATA INFILE
C:/Users/Manuel Montiel/Documents/MySQL/ramadb/insert_departamento.txt
INTO TABLE departamento;
LOAD DATA INFILE C:/Users/Manuel
Montiel/Documents/MySQL/ramadb/insert_estudiante.txt INTO TABLE
estudiante;
LOAD DATA INFILE C:/Users/Manuel
Montiel/Documents/MySQL/ramadb/insert_matricula.txt INTO TABLE matricula;
LOAD DATA INFILE C:/Users/Manuel
Montiel/Documents/MySQL/ramadb/insert_curso.txt INTO TABLE curso;
LOAD DATA INFILE C:/Users/Manuel
Montiel/Documents/MySQL/ramadb/insert_claustro.txt INTO TABLE claustro;
MariaDB [educa]> UPDATE departamento SET dept=CISS WHERE dept= CIS;
MariaDB [educa]> UPDATE estudiante SET esp=CISS WHERE esp= CIS;
MariaDB [educa]> SELECT * FROM curso WHERE tarifa<150;
MariaDB [educa]> SELECT * FROM curso WHERE nombre >=ESTRUCTURA;
MariaDB [educa]> SELECT num, nombre, descripcion FROM curso WHERE
nombre BETWEEN ES AND FUND;
MariaDB [educa]> SELECT num, tarifa FROM curso WHERE tarifa BETWEEN 50
AND 400;
MariaDB [educa]> SELECT * FROM curso WHERE tarifa NOT IN (12, 15, 50, 75,
90, 100, 500);
MariaDB [educa]> SELECT * FROM curso WHERE descripcion LIKE PARA %;
MariaDB [educa]> SELECT nombre, numdept, fdept FROM claustro WHERE
numdept IS NOT NULL;
MariaDB [educa]> SELECT * FROM curso WHERE red=3 AND cdept=PHIL;
MariaDB [educa]> SELECT * FROM curso WHERE (tarifa>=100) AND
(tarifa<=500);
MariaDB [educa]> SELECT nombre, cuota, ventas FROM repventas WHERE
ventas < cuota AND ventas < 300000;
MariaDB [educa]> SELECT nombre, cuota, ventas FROM repventas WHERE
ventas < cuota OR ventas < 300000;
MariaDB [educa]> SELECT sueldo FROM personal UNION SELECT sueldo FROM
claustro;
MariaDB [educa]> SELECT sueldo FROM personal UNION ALL SELECT sueldo
FROM claustro;
MariaDB [educa]> SELECT idfab, idproducto FROM productos WHERE precio >
2000 UNION SELECT fab, producto FROM pedidos WHERE importe > 3000;

MariaDB [educa]> SELECT idfab, idproducto FROM productos WHERE precio >
2000 UNION ALL SELECT fab, producto FROM pedidos WHERE importe > 3000;
MariaDB [educa]> SELECT idfab, idproducto FROM productos WHERE precio >
2000 UNION ALL SELECT DISTINCT fab, producto FROM pedidos WHERE importe
> 3000;
MariaDB [educa]> SELECT idfab, idproducto FROM productos WHERE precio >
2000 UNION ALL SELECT DISTINCT fab, producto FROM pedidos WHERE importe
> 3000 ORDER BY 1,2;
MariaDB [educa]> SELECT cdept, nombre FROM curso ORDER BY cdept,
nombre;
MariaDB [educa]> SELECT * FROM curso WHERE NOT cdept=CISS OR
(tarifa=0 AND red=3);
MariaDB [educa]> SELECT * FROM curso WHERE cdept IN(CISS,THEO) AND
tarifa BETWEEN 50 AND 300 AND RED=3 ORDER BY cdept, nombre;
MariaDB [educa]> SELECT * FROM curso WHERE nombre NOT LIKE _A% OR
nombre NOT LIKE _E% OR _I% OR _O% OR _U%;
MariaDB [educa]> SELECT nombre, tarifa tarifa/red AS TARIFA_POR_CREDITO,
(tarifa+25)/red AS TARIFA_MEDIA_POR_HORA FROM curso WHERE cdept=CISS;
MariaDB [educa]> SELECT tarifa, SUM(red) AS CREDITOS_TOTALES FROM curso
GROUP BY tarifa ORDER BY tarifa DESC;
MariaDB [educa]> SELECT cdept, AVG(tarifa) FROM curso GROUP BY curso
HAVING AVG(tarifa)>100 AND COUNT(*)<6;
MariaDB [educa]> SELECT DISTINCT cdept, red FROM curso WHERE tarifa<100;
MariaDB [educa]> SELECT num, nombre CURSO CARO FROM curso WHERE
tarifa >100;
MariaDB [educa]> SELECT num, nombre, red FROM curso WHERE cdept=CISS
ORDER BY num DESC;
MariaDB [educa]> SELECT cdept, nombre FROM curso ORDER BY cdept,
nombre;
MariaDB [educa]> SELECT * FROM curso WHERE tarifa=0 AND cdept=CISS;
MariaDB [educa]> SELECT * FROM curso WHERE tarifa=0 AND tarifa<100;
MariaDB [educa]> SELECT * FROM curso BETWEEN 0 AND 100 AND
cdept=PHIL AND red=3;
MariaDB [educa]> SELECT * FROM curso WHERE cdept=CISS OR
cdept=PHIL;
MariaDB [educa]> SELECT * FROM curso WHERE cdept=CISS OR tarifa=0;
MariaDB [educa]> SELECT * FROM curso WHERE tarifa=50 OR tarifa=100 OR
tarifa=150;
MariaDB [educa]> SELECT cdept, nombre FROM curso WHERE NOT
(cdept=CISS) AND NOT (cdept=PHIL);
MariaDB [educa]> SELECT * FROM curso WHERE cdept=THEO AND tarifa=0
OR red=6;
MariaDB [educa]> SELECT * FROM curso WHERE cdept=THEO AND (tarifa=0
OR red=6);
MariaDB [educa]> SELECT * FROM curso WHERE NOT (cdept=CISS) OR
tarifa=0 AND red=3;
MariaDB [educa]> SELECT * FROM curso WHERE NOT (cdept=CISS AND
tarifa=0);
MariaDB [educa]> SELECT * FROM curso WHERE red IN (2,6,9);
MariaDB [educa]> SELECT * FROM curso WHERE cdept NOT IN (THEO,CISS);
MariaDB [educa]> SELECT * FROM curso WHERE tarifa BETWEEN 100 AND 200;

MariaDB [educa]> SELECT * FROM curso WHERE tarifa NOT BETWEEN 100 AND
200;
MariaDB [educa]> SELECT * FROM curso WHERE nombre BETWEEN C AND
CZZ;
MariaDB [educa]> SELECT * FROM curso WHERE cdept IN (CISS, THEO, DIR)
AND tarifa BETWEEN 50 AND 300 AND red=3 ORDER BY cdept, nombre;
MariaDB [educa]> SELECT * FROM curso WHERE nombre LIKE INTRODUD%;
MariaDB [educa]> SELECT * FROM curso WHERE nombre LIKE %SC%;
MariaDB [educa]> SELECT DISTINCT cdept FROM curso WHERE cdept LIKE %S
OR cdept LIKE %S OR cdept LIKE %S OR cdept LIKE %S ;
MariaDB [educa]> SELECT * FROM curso WHERE cdept LIKE _H%;
MariaDB [educa]> SELECT * FROM curso WHERE nombre LIKE _A% OR nombre
LIKE _E% OR nombre LIKE _I% OR nombre LIKE _O% OR nombre LIKE _U%;
MariaDB [educa]> SELECT * FROM curso WHERE nombre NOT LIKE _A% OR
nombre NOT LIKE _E% OR nombre NOT LIKE _I% OR nombre NOT LIKE _O%
OR nombre NOT LIKE _U%;
MariaDB [educa]> SELECT nombre, tarifa, tarifa+25 AS NUEVA TARIFA FROM
curso WHERE cdept=CISS;
MariaDB [educa]> SELECT nombre, tarifa, tarifa+25 AS NUEVA TARIFA FROM
curso WHERE cdept=CISS ORDER BY 3;
MariaDB [educa]> SELECT nombre, tarifa, tarifa/red AS TARIFA POR CREDITO
FROM curso WHERE cdept=CISS AND tarifa/red<30;
MariaDB [educa]> SELECT * FROM curso, departamento WHERE cdept= dept;
MariaDB [educa]> SELECT nombre, tarifa chfno FROM curso, departamento
WHERE cdept=dept AND tarifa>100;
MariaDB [educa]> SELECT nombre, sueldo, tarifa, tarifa-sueldo AS DIFERENCIA
FROM personal, curso WHERE dept=cdept AND (tarifa-sueldo)>=52;
MariaDB [educa]> SELECT clase.num, curso.nombre, claustro.num,
matricula.num FROM curso, clase, claustro, matricula WHERE curso.num=
clase.num AND clase.num= matricula.num AND matricula.sec= clase.sec and
matricula.sec=02 ;
MariaDB [educa]> SELECT AVG(tarifa) AS MEDIA, MAX(tarifa) AS MAXIMO,
MIN(tarifa) AS MINIMO FROM curso WHERE cdept=CISS AND tarifa<>0;
MariaDB [educa]> SELECT MIN(nombre) PRIMER CURSO FROM curso;
MariaDB [educa]> SELECT COUNT(*) AS CURSOS, SUM(tarifa) AS TARIFA
TOTAL FROM curso WHERE cdept=PHIL;
MariaDB [educa]> SELECT dept AS NOMBRE, COUNT(*) AS MIEMBROS FROM
personal GROUP BY dept;
MariaDB [educa]> SELECT cdept AS DEPARTAMENTO, SUM(red) AS CREDITOS
FROM curso GROUP BY cdept;
MariaDB [educa]> SELECT cdept AS DEPARTAMENTO, SUM(tarifa) AS TARIFA
FROM curso WHERE red<>6 GROUP BY cdept;
MariaDB [educa]> SELECT * FROM personal, departamento WHERE
personal.dept= departamento.dept;
MariaDB [educa]> SELECT nombre, sueldo, personal.dept, edif, despacho FROM
personal, departamento WHERE personal.dept=departamento.dept AND sueldo
>100;
MariaDB [educa]> SELECT nombre, tarifa, chfno FROM curso WHERE
cdept=dept AND tarifa>175 ORDER BY nombre;
MariaDB [educa]> SELECT nombre, cargo FROM personal, departamento
WHERE personal.dept = departamento.dept AND edif=HU;

MariaDB [educa]> SELECT dept, AVG(tarifa) TARIFA MEDIA, AVG(sueldo)


SUELDO MEDIO FROM personal, curso WHERE dept=cdept GROUP BY dept
ORDER BY dept;
MariaDB [educa]> SELECT num, nombre, cargo, edif, despacho FROM personal,
curso, departamento WHERE cdept=personal.dept AND
cdept=departamento.dept ORDER BY num, nombre;
MariaDB [educa]> SELECT cdept, AVG(tarifa) AS TARIFA MEDIA FROM curso
WHERE NOT (cdept=THEO) GROUP BY cdept HAVING AVG(tarifa) > 100;
MariaDB [educa]> SELECT SELECT PER1.dept, PER1.nombre, PER2.nombre
FROM personal PER1, personal PER2 WHERE PER1.dept = PER2.dept;
MariaDB [educa]> SELECT tarifa, SUM(red) AS CREDITOS TOTALES FROM
curso GROUP BY tarifa ORDER BY tarifa DESC;
MariaDB [educa]> SELECT cdept, red, AVG(tarifa) AS TARIFA MEDIA,
MAX(tarifa) AS TARIFA MAXIMA, MIN(tarifa) AS TARIFA MINIMA FROM curso
GROUP BY cdept, red HAVING MIN(tarifa9 > 0;
MariaDB [educa]> SELECT cdept, AVG(tarifa) AS TARIFA MEDIA FROM curso
GROUP BY cdept HAVING AVG(tarifa) > 100 AND COUNT()>6;
MariaDB [educa]> SELECT SUBSTRING(horamat,1,5) AS HORA Y MINUTOS,
SUBSTRING(horamat,1,8) AS HORA Y MINUTOS Y SEGUNDOS FROM matricula;
MariaDB [educa]>
MariaDB [educa]>
MariaDB [educa]>
MariaDB [educa]>
MariaDB [educa]>

DATABASE empresa
MariaDB [none]> USE empresa;
SOURCE C:/Users/Manuel
Montiel/Documents/MySQL/empresa/crear_tablas_empresa.sql;
LOAD DATA INFILE C:/Users/Manuel
Montiel/Documents/MySQL/empresa/insert_clientes.txt INTO TABLE clientes;
LOAD DATA INFILE C:/Users/Manuel
Montiel/Documents/MySQL/empresa/insert_repventas.txt INTO TABLE
repventas;
LOAD DATA INFILE C:/Users/Manuel
Montiel/Documents/MySQL/empresa/insert_oficinas.txt INTO TABLE oficinas;
LOAD DATA INFILE C:/Users/Manuel
Montiel/Documents/MySQL/empresa/insert_productos.txt INTO TABLE
productos;
LOAD DATA INFILE C:/Users/Manuel
Montiel/Documents/MySQL/empresa/insert_pedidos.txt INTO TABLE pedidos;
MariaDB [empresa]> SHOW TABLE STATUS FROM empresa;
MariaDB [empresa]> SHOW VARIABLES LIKE version%;
MariaDB [empresa]> EXPLAIN repventas;
MariaDB [empresa]> SHOW COLUMNS FROM repventas; // equivale a la
anterior

MariaDB [empresa]> OPTIMIZE TABLE clientes;


MariaDB [empresa]> LOCK TABLE clientes READ;
// Se establece para solo
lectura
MariaDB [empresa]> SELECT * FROM clientes INTO OUTFILE C:/Users/Manuel
Montiel/Documents/MySQL/empresa/select_clientes.txt;
MariaDB [empresa]> SELECT ciudad, ventas, objetivo FROM oficinas WHERE
ventas > objetivo;
MariaDB [empresa]> SELECT nombre, ventas, cuota FROM repventas WHERE
numempl=105;
MariaDB [empresa]> SELECT * FROM productos ORDER BY precio DESC;
MariaDB [empresa]> SELECT ciudad, region, ventas FROM oficinas ORDER BY
region, ciudad;
MariaDB [empresa]> SELECT ciudad, region, ventas FROM oficinas ORDER BY
ventas DESC;
MariaDB [empresa]> SELECT ciudad, region, ventas FROM oficinas ORDER BY 3
DESC;
MariaDB [empresa]> SELECT ciudad, region, ventas FROM oficinas ORDER BY
region ASC, 3 DESC;
MariaDB [empresa]> SELECT ciudad, region, ventas-objetivo AS RENDIMIENTO
FROM oficinas;
MariaDB [empresa]> SELECT ciudad, region, ventas-objetivo RENDIMIENTO
FROM oficinas;
MariaDB [empresa]> SELECT idfab, idproducto descripcin, existencias*precio
AS INVENTARIO FROM productos;
MariaDB []> SELECT nombre, cuota, cuota+0.03*ventas AS CUOTA_ELEVADA
FROM repventas;
MariaDB [empresa]> SELECT nombre FROM repventas WHERE contrato <
1988-01-01;
MariaDB [empresa]> SELECT * FROM oficinas WHERE ventas < 0.8*objetivo;
MariaDB [empresa]> SELECT empresa, limitecredito FROM clientes WHERE
numclie= 2124;
MariaDB [empresa]> SELECT * FROM pedidos WHERE fechapedido BETWEEN
1989-10-01 AND 1989-12-31;
MariaDB [empresa]> SELECT * FROM repventas WHERE ventas NOT BETWEEN
0.8*cuota AND 1.2*cuota;
MariaDB [empresa]> SELECT * FROM repventas WHERE oficinarep IN (11, 13,
22);
MariaDB [empresa]> SELECT numpedido, fechapedido, importe FROM pedidos
WHERE fechapedido NOT IN (1990-01-04, 1990-01-11, 1990-01-18);
MariaDB [empresa]> SELECT empresa, limitecredito FROM clientes WHERE
empresa LIKE Smith%;
MariaDB [empresa]> SELECT * FROM clientes WHERE limitecredito NOT LIKE
20000;
MariaDB [empresa]> SELECT * FROM clientes WHERE empresa LIKE A_%;
MariaDB [empresa]> UPDATE repventas SET director=104, cuota=275000,
ventas=286775 WHERE numempl= 103;
MariaDB [empresa]> SELECT idfab, idproducto FROM pedidos WHERE precio >
2000 UNION SELECT DISTINCT fab, producto FROM pedidos WHERE importe >
30000;
MariaDB [empresa]> SELECT pedidos.numpedido, pedidos.importe,
clientes.empresa, clientes.limitecredito FROM pedidos, clientes WHERE
clie=numclie;

MariaDB [empresa]> SELECT numpedido, importe, empresa, limitecredito


FROM pedidos, clientes WHERE clie= numclie;
MariaDB [empresa]> SELECT nombre, ciudad, region FROM repventas, oficinas
WHERE oficinarep = oficina;
MariaDB [empresa]> SELECT nombre, ciudad, titulo FROM repventas, oficinas
WHERE dir=numempl;
MariaDB [empresa]> SELECT nombre, ciudad, titulo FROM repventas, oficinas
WHERE dir=numempl AND objetivo < 600000;
MariaDB [empresa]> SELECT numpedido, importe, descripcin FROM pedidos,
productos WHERE fab=idfab AND producto=idproducto;
MariaDB [empresa]> SELECT numpedido, importe, empresa, nombre FROM
pedidos, clientes, repventas WHERE clie=numclie AND rep=numempl AND
importe > 25000;
MariaDB [empresa]> SELECT numpedido, importe, empresa, nombre FROM
pedidos, clientes, repventas WHERE clie= numclie AND repclie=numempl AND
importe>25000;
MariaDB [empresa]> SELECT numpedido, importe, empresa, nombre, ciudad
FROM pedidos, clientes, repventas, oficinas WHERE clie= numclie AND
repclie=numempl AND oficinarep=oficina AND importe>25000;
MariaDB [empresa]> SELECT numpedido, importe, fechapedido, nombre FROM
pedidos, repventas WHERE fechapedido=contrato;
MariaDB [empresa]> SELECT nombre, cuota, ciudad, objetivo FROM repventas,
oficinas WHERE cuota>objetivo;
MariaDB [empresa]> SELECT nombre, cuota, ciudad, objetivo FROM repventas,
oficinas WHERE cuota-objetivo > 0;
MariaDB [empresa]> SELECT nombre, ciudad FROM repventas, oficinas WHERE
oficinarep=oficina;
MariaDB [empresa]> SELECT nombre, ciudad, oficinarep, numempl, dir FROM
repventas, oficinas WHERE numempl= dir;
MariaDB [empresa]> SELECT nombre, ciudad, oficinarep, numempl, dir FROM
repventas LEFT JOIN oficinas ON numempl= dir;
SELECT nombre, ciudad, oficinarep, numempl, dir FROM repventas RIGHT JOIN
oficinas ON numempl= dir;
MariaDB [empresa]> SELECT nombre, ciudad, oficinarep, numempl, dir FROM
repventas INNER JOIN oficinas ON numempl= dir;
MariaDB [empresa]> SELECT nombre, titulo, objetivo, oficina, ciudad FROM
repventas INNER JOIN oficinas ON oficinarep= oficinas;
MariaDB [empresa]> SELECT empresa, numpedido, importe FROM clientes
INNER JOIN pedidos ON numclie= clie AND numclie=2103;
MariaDB [empresa]> SELECT empresa, numpedido, importe FROM clientes
LEFT JOIN pedidos ON numclie= clie AND numclie=2103;
MariaDB [empresa]> SELECT empresa, numpedido, importe FROM clientes
RIGHT JOIN pedidos ON numclie= clie AND numclie=2103;
MariaDB [empresa]> SELECT repventas.*, ciudad, regin FROM repventas,
oficinas WHERE oficinarep= oficina;
MariaDB [empresa]> SELECT emps.nombre, dirs.nombre FROM repventas
emps, repventas dirs WHERE emps.director= dirs.numempl;
MariaDB [empresa]> SELECT repventas.nombre, dirs.nombre FROM repventas,
repventas dirs WHERE repventas.director= dirs.numempl;
MariaDB [empresa]> SELECT repventas.nombre, repventas.cuota, dirs.cuota
FROM repventas, repventas dirs WHERE repventas.director=dirs.numempl AND
repventas.cuota>dirs.cuota;

MariaDB [empresa]> SELECT s1.nombre, s1.sueldo, s2.nombre FROM personal


s1, personal s2 WHERE s1.sueldo-s2.sueldo > 100;
MariaDB [empresa]> SELECT AVG(cuota) CUOTA PROMEDIO, AVG(ventas)
VENTAS PROMEDIO, AVG(100*(ventas/cuota)) RENDIMIENTO DE CUOTA
PROMEDIO FROM repventas;
MariaDB [empresa]> SELECT MAX(100*(ventas/cuota) AS RENDIMIENTO
OPTIMO DE VENTAS FROM repventas;
MariaDB [empresa]> SELECT SUM(cuota) TOTAL, SUM(ventas) VENTAS
TOTALES, MIN(cuota) CUOTA MINIMA, MAX(cuota) CUOTA MAXIMA FROM
repventas;
MariaDB [empresa]> SELECT SUM(importe) IMPORTE TOTAL, AVG(importe9,
IMPORTE MEDIO FROM pedidos, repventas WHERE nombre=Bill Adams AND
rep=numempl;
MariaDB [empresa]> SELECT AVG(precio) AS PRECIO MEDIO FROM productos
WHERE idfab=ACI;
MariaDB [empresa]> SELECT COUNT(*) AS VENDEDORES FROM repventas
WHERE ventas>cuotas;
MariaDB [empresa]> SELECT COUNT(*) AS PEDIDOS FROM pedidos WHERE
importe>25000;
MariaDB [empresa]> SELECT COUNT (DISTINCT titulo) AS TITULOS FROM
repventas;
MariaDB [empresa]> SELECT COUNT (titulo) AS TITULOS FROM repventas;
MariaDB [empresa]> SELECT COUNT (DISTINCT oficinarep) AS VENDEDORES
FROM repventas WHERE ventas>cuota;
MariaDB [empresa]> SELECT rep AS VENDEDOR, AVG(importe) AS PEDIDO
MEDIO FROM pedidos GROUP BY rep;
MariaDB [empresa]> SELECT oficinarep AS OFICINA, COUNT(*) AS N DE
VENDEDORES FROM repventas GROUP BY oficinarep;
MariaDB [empresa]> SELECT rep AS VENDEDOR, clie AS CLIENTE,
SUM(importe) AS PEDIDO TOTAL FROM pedidos GROUP BY rep, clie;
MariaDB [empresa]> SELECT rep AS VENDEDOR, clie AS CLIENTE,
SUM(importe) AS PEDIDO TOTAL FROM pedidos GROUP BY rep, clie ORDER BY
rep, clie;
MariaDB [empresa]> SELECT numempl AS EMPLEADO, nombre, SUM(importe)
AS PEDIDO TOTAL FROM pedidos, repventas WHERE rep=numempl GROUP BY
numempl, nombre;
MariaDB [empresa]> SELECT rep AS VENDEDOR, AVG(importe) AS PEDIDO
MEDIO FROM pedidos GROUP BY rep HAVING SUM(importe) SUM(importe) >
30000;
MariaDB [empresa]> SELECT ciudad, SUM(cuota) AS CUOTA,
SUM(repventas.ventas) AS VENTAS FROM oficinas, repventas WHERE
oficina=oficinarep GROUP BY ciudad HAVING COUNT(*) > 2;
MariaDB [empresa]> SELECT rep, AVG(importe) AS IMPORTE MEDIO FROM
pedidos WHERE importe>20000 GROUP BY rep HAVING SUM(importe) > 30000;
MariaDB [empresa]> SELECT rep, AVG(importe) AS IMPORTE MEDIO FROM
pedidos GROUP BY rep HAVING SUM(importe) > 30000 OR AVG(importe) >
6000;
MariaDB [empresa]> SELECT UCASE(ciudad) AS MAYUSCULAS,
LCASE(ciudad) AS MINUSCULAS, LENGTH(ciudad) AS N DE CARACTERES
FROM oficinas;
MariaDB [empresa]> SELECT nombre, LOCATE(A,nombre) AS PRIMERA
OCURRENCIA DE A FROM repventas;

MariaDB [empresa]> SELECT nombre, LOCATE(A,SUBSTRING(nombre,


LOCATE(A,nombre)+1, LENGTH(nombre))) AS CARACTERES DESDE LA
PRIMERA A LA SEGUNDA OCURRENCIA DE A FROM repventas;
MariaDB [empresa]> SELECT fab, cant, importe FROM pedidos WHERE
SOUNDEX(fab)= SOUNDEX(ACI);
MariaDB [empresa]> SELECT CONCAT(ciudad,, ,region) AS UBICACIN FROM
oficinas;
MariaDB [empresa]> SELECT RPAD(ciudad, 35, .), region FROM oficinas;
MariaDB [empresa]> SELECT CONCAT(ventas, ,, 00) FROM repventas;
MariaDB [empresa]> SELECT SUBSTRING(contrato,1,7),
SUBSTRING(contrato,6,8) FROM repventas;
MariaDB [empresa]> SELECT nombre, ventas/cuota AS RATIO,
ROUND(ventas/cuota,5) AS RATIO REDONDEADO FROM repventas;
MariaDB [empresa]> SELECT nombre, ventas/cuota AS RATIO,
CEILING(ventas/cuota) AS PARTE ENTERA + 1, FLOOR(ventas/cuota) AS
PARTE ENTERA FROM repventas;
MariaDB [empresa]> SELECT ventas, LOG(ventas) NEPERIANO,
LOG10(ventas) LOG. DECIMAL, POWER(ventas, 2) AS CUADRADO,
SQRT(ventas) AS RAIZ CUADRADA FROM repventas;
MariaDB [empresa]> SELECT oficinarep, SUM(ventas) SUMA, AVG(ventas)
VENTAS MEDIAS, MAX(ventas) VENTAS MXIMAS, MIN(ventas) VENTAS
MNIMAS FROM repventas GROUP BY oficinarep;
MariaDB [empresa]> SELECT oficinarep, STD(ventas) DESVIACIN TPICA,
POWER(STD(ventas),2 ) VARIANZA FROM repventas GROUP BY oficinarep;
MariaDB [empresa]> SELECT COUNT(cuota)CUOTAS, COUNT(DISTINCT cuota)
CUOTAS DISTINTAS, AVG(cuota) CUOTA MEDIA FROM repventas;
MariaDB [empresa]> SELECT ( MAX(ventas) MIN(ventas) )/2 AS EXTREMO
SUPERIOR FROM repventas GROUP BY oficinarep;
MariaDB [empresa]>
DATABASE plantillaempresa
MariaDB [none]> USE DATABASE plantillaempresa;
MariaDB [plant]> SELECT nombre FROM plantilla UNION SELECT nombre
FROM posterior;
MariaDB [plant]> SELECT nombre FROM plantilla UNION ALL SELECT nombre
FROM posterior;
MariaDB [plant]> SELECT nombre, alojamiento FROM plantilla UNION SELECT
nombre, direccion FROM posterior;
MariaDB [plant]> SELECT nombre, alojamiento FROM plantilla UNION ALL
SELECT nombre, direccion FROM posterior;
MariaDB [plant]> SELECT nombre, alojamiento FROM plantilla UNION SELECT
nombre, direccin, 0 FROM posterior;
MariaDB [plant]> SELECT nombre, alojamiento FROM plantilla UNION ALL
SELECT nombre, direccin, 0 FROM posterior;
MariaDB [plant]>
MariaDB [plant]>
MariaDB [plant]>