Comprendiendo comandos SQL en la BD de clientes y ventas

Guía para crear una base de datos de clientes y ventas con SQL: esquemas, tablas, claves y consultas, mejores prácticas y soluciones en AWS/Azure con Q2BSTUDIO.

17 ago 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Construyendo una base de datos de clientes y ventas con SQL

Introducción: En este artículo explicamos paso a paso cómo crear una base de datos relacional que rastrea clientes, productos y ventas usando sentencias SQL básicas. También mostramos consultas para obtener información útil y destacamos cómo Q2BSTUDIO puede ayudar con soluciones de software a medida, aplicaciones a medida, inteligencia artificial, ciberseguridad y servicios cloud aws y azure.

1 Configuración de la base de datos y esquema: Primero creamos la base y un esquema para organizar las tablas

SQL Ejemplo CREATE DATABASE jamii_db; CREATE SCHEMA customers;

Por qué usar esquemas: permiten agrupar tablas relacionadas y facilitar la gestión de permisos y despliegue en entornos cloud como servicios cloud aws y azure.

2 Creación de tablas con relaciones: Definimos tres tablas con claves primarias y claves foráneas para mantener integridad referencial

Tabla customer_info que almacena datos de clientes SQL CREATE TABLE customers.customer_info ( customer_id INT PRIMARY KEY, fullname VARCHAR(100), location VARCHAR(100) );

Tabla products que asocia productos a clientes SQL CREATE TABLE customers.products ( product_id INT PRIMARY KEY, customer_id INT, product_name VARCHAR(100), price FLOAT, FOREIGN KEY (customer_id) REFERENCES customers.customer_info (customer_id) );

Tabla sales que registra ventas vinculadas a productos y clientes SQL CREATE TABLE customers.sales ( sales_id INT PRIMARY KEY, product_id INT, customer_id INT, total_sales INT, FOREIGN KEY (product_id) REFERENCES customers.products (product_id), FOREIGN KEY (customer_id) REFERENCES customers.customer_info (customer_id) );

Clave importante: las foreign keys garantizan integridad de datos entre tablas y son fundamentales para soluciones empresariales que combinan inteligencia artificial e inteligencia de negocio.

3 Inserción de datos de ejemplo

Insertar clientes SQL INSERT INTO customers.customer_info (customer_id, fullname, location) VALUES (1, James Mwangi, Rwanda), (2, Akello Kel, Amboseli), (3, Judy J, Nanyuki), (4, Ahab Jez, Israel);

Insertar productos SQL INSERT INTO customers.products (product_id, customer_id, product_name, price) VALUES (1, 1, Laptop, 20000), (2, 2, Mouse, 1500), (3, 3, Charger, 4000);

Insertar ventas SQL INSERT INTO customers.sales (sales_id, product_id, customer_id, total_sales) VALUES (1, 1, 1, 300000), (2, 2, 2, 450000), (3, 3, 3, 100000), (4, 1, 1, 200000), (5, 2, 2, 350000), (6, 3, 3, 150000);

Nota: el cliente con customer_id 4 no tiene ventas registradas, útil para mostrar consultas de clientes sin compras y para acciones de retención mediante agentes IA.

4 Consultas básicas y avanzadas

A Consultar todos los clientes SELECT * FROM customers.customer_info;

B Obtener solo nombres y ubicaciones SELECT fullname, location FROM customers.customer_info;

Consulta: Qué compró cada cliente SELECT c.fullname, p.product_name, s.total_sales FROM customers.customer_info c JOIN customers.sales s ON c.customer_id = s.customer_id JOIN customers.products p ON s.product_id = p.product_id;

Consulta: Ventas totales por cliente SELECT ci.fullname, SUM(s.total_sales) AS sales_total FROM customers.sales s JOIN customers.customer_info ci ON s.customer_id = ci.customer_id GROUP BY ci.fullname ORDER BY sales_total DESC;

Consulta: Producto con mayor facturación SELECT p.product_name, SUM(s.total_sales) AS sales_total FROM customers.sales s JOIN customers.products p ON s.product_id = p.product_id GROUP BY p.product_name ORDER BY sales_total DESC LIMIT 1;

Consulta: Clientes sin compras SELECT fullname FROM customers.customer_info ci LEFT JOIN customers.sales s ON ci.customer_id = s.customer_id WHERE s.sales_id IS NULL;

5 Buenas prácticas y extenciones: Usar índices en columnas de join para mejorar rendimiento, aplicar validaciones en el modelo de datos y automatizar backups en servicios cloud aws y azure. Combinar esta base con pipelines de datos y power bi para crear paneles que integren servicios inteligencia de negocio y mostrar insights impulsados por inteligencia artificial e ia para empresas.

Sobre Q2BSTUDIO: Q2BSTUDIO es una empresa de desarrollo de software y aplicaciones a medida especializada en soluciones empresariales, software a medida, inteligencia artificial, ciberseguridad, agentes IA, servicios cloud aws y azure y servicios inteligencia de negocio. Ofrecemos consultoría, desarrollo de aplicaciones a medida, integración de power bi y despliegue seguro en la nube. Nuestro equipo diseña arquitecturas que combinan modelos de inteligencia artificial con prácticas de ciberseguridad para garantizar rendimiento y protección.

Conclusión: Hemos mostrado cómo construir una base de datos relacional para clientes y ventas, cómo insertar datos y cómo obtener insights con consultas SQL. Si deseas potenciar tu proyecto con software a medida, inteligencia artificial o soluciones cloud, contacta a Q2BSTUDIO para una propuesta que incluya desarrollo de aplicaciones a medida, agentes IA y dashboards con power bi.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat