Database Administrators
Q&A for database professionals who wish to improve their database skills
Latest Questions
0
votes
2
answers
3070
views
SQL to check if a certain time duration occurs within a particular period of the day
I'm working with data that has a start datetime and end datetime column for each event which can be a short period of time (Few hours) up to a number of days in duration. I'm trying to establish a way to check for where the following is true: 1. the duration between the start and end datetimes is gr...
I'm working with data that has a start datetime and end datetime column for each event which can be a short period of time
(Few hours) up to a number of days in duration.
I'm trying to establish a way to check for where the following is true:
1. the duration between the start and end datetimes is greater than 6 hours
And
2. this duration takes place between the hours of 09:00 and 17:00 (on any of the dates within the period if it was a long duration e.g. 36hrs)
If the total duration of 6hrs is met but any of those 6hrs falls outwith these hours, then I don't want to count it.
E.g.
01/05/23 09:00 to 01/05/23 16:30 - true
01/05/23 08:30 to 01/05/23 14:30 - false
01/05/23 10:00 to 01/05/23 17:30 - true
01/05/23 11:00 to 02/05/23 01:00 - true
01/05/23 12:00 to 02/05/23 02:30 - false
I have tried setting up a basic case when to check where datediff >= 6 and check that the end time > start time (incase of any data quality issues with dates recorded) but struggling to come up with a way to check for the datediff >= 6 being met within the 09:00 and 17:00 period and tie the two conditions together.
I'm looking to add this to a large data set so looking for something that hopefully won't affect performance too much as I remember doing something before where I listed rows by the hour within a duration but it had a knock on effect on performance due to the vast amount of rows created to do this.
I was wondering if anyone has any ideas on the best way I can achieve this? Thanks in advance.
DynamoRanger
(13 rep)
May 29, 2023, 07:54 PM
• Last activity: May 11, 2025, 07:10 PM
-1
votes
1
answers
49
views
MySQL code error
Can someone please tell what is wrong with below SQL code? CREATE TABLE student ( student_id INT PRIMARY KEY, first_name VARCHAR(20), major VARCHAR(20), );
Can someone please tell what is wrong with below SQL code?
CREATE TABLE student (
student_id INT PRIMARY KEY,
first_name VARCHAR(20),
major VARCHAR(20),
);
Lalita Joshi
(1 rep)
Jun 29, 2022, 05:32 AM
• Last activity: Jun 29, 2022, 12:21 PM
-1
votes
2
answers
2113
views
I want to select many columns from many tables without foreign key
I have three tables, and I want to fetch the three table data without a foreign key. Say I have a table product_1 which contains (id, name) and table product_2 contain (id, name, price). I want to select the columns of the two tables in one query. I am asking if there are any MySQL query to select m...
I have three tables, and I want to fetch the three table data without a foreign key.
Say I have a table product_1 which contains (id, name) and table product_2 contain (id, name, price).
I want to select the columns of the two tables in one query.
I am asking if there are any MySQL query to select many columns from many tables?
This is my code:
SELECT name FROM product1 AND price FROM product2;
znzoony
(1 rep)
Jan 23, 2022, 02:23 PM
• Last activity: Jan 24, 2022, 06:21 PM
1
votes
2
answers
1335
views
How can I get this code to work? It's in mysql, I keep getting an error 1822' failed to add foreign key constraint. Missing index for constraint'
CREATE TABLE EMPLOYEE ( employeeNumber VARCHAR (15) NOT NULL, employeeName VARCHAR (20) NOT NULL, department VARCHAR (10) NOT NULL, phone INT NOT NULL, PRIMARY KEY (employeeName, department) CREATE TABLE DEPARTMENTS( department VARCHAR (10) NOT NULL, department Code VARCHAR(10) NOT NULL, department...
CREATE TABLE EMPLOYEE (
employeeNumber VARCHAR (15) NOT NULL,
employeeName VARCHAR (20) NOT NULL,
department VARCHAR (10) NOT NULL,
phone INT NOT NULL,
PRIMARY KEY (employeeName, department)
CREATE TABLE DEPARTMENTS(
department VARCHAR (10) NOT NULL,
department Code VARCHAR(10) NOT NULL,
department Name VARCHAR(30) NOT NULL,
FOREIGN KEY (department)
REFERENCES EMPLOYEE (department)
CREATE TABLE EMAIL_INFO(
employee Name VARCHAR (20) NOT NULL,
email VARCHAR (30) NOT NULL,
FOREIGN KEY (employeeName)
REFERENCES EMPLOYEE (employeeName)
);
Enrisen Tzib
(13 rep)
Jun 3, 2020, 03:08 PM
• Last activity: Jun 3, 2020, 04:02 PM
1
votes
1
answers
54
views
Does CUBRID have Information Schema Views?
**I am trying to access the Information Schema views as defined in SQL92, and cannot find any in the CUBRID RDBMS. Has CUBRID implemented this specification and how can I access them?** CUBRID version: CUBRID 10.1, manual: https://www.cubrid.org/manual/en/10.1/ **There is something called System Cat...
**I am trying to access the Information Schema views as defined in SQL92, and cannot find any in the CUBRID RDBMS. Has CUBRID implemented this specification and how can I access them?**
CUBRID version: CUBRID 10.1, manual: https://www.cubrid.org/manual/en/10.1/
**There is something called System Catalog: https://www.cubrid.org/manual/en/10.1/sql/catalog.html , is this possibly the same, and why is it not called "information_schema" as specified in the SQL92 specification?**
When querying the database for my table
book
i get following:
SELECT * FROM db_class WHERE class_name LIKE 'book';
class_name = book
owner_name = DBA
class_type = CLASS
is_system_class = NO
partitioned = NO
is_reuse_oid_class = YES
collation = iso88591_bin
comment =
**Are there no schemas in CUBRID?**
Configuration configuration = new Configuration()
.withJdbc(new Jdbc()
.withDriver(DRIVER)
.withUrl(URI))
.withGenerator(new Generator()
.withGenerate(new Generate()
.withDaos(true)
.withImmutablePojos(true))
.withDatabase(new Database()
.withName(DATABASE)
// .withIncludes(".*")
// .withExcludes("")
.withInputSchema("jq"))
.withTarget(new Target()
.withPackageName(PACKAGE)
.withDirectory(DIRECTORY)
.withClean(true)))
.withLogging(Logging.TRACE);
GenerationTool.generate(configuration);
**I need it for code-generation with JOOQ, what catalog/schema do I have to specify?**
Erdinc Ay
(167 rep)
Aug 21, 2019, 03:17 PM
• Last activity: Aug 21, 2019, 03:54 PM
7
votes
2
answers
27174
views
Best practices for committing a transaction in SQL Server where TRY CATCH is used
In a SQL Server code block, what is the best place to place the commit transaction? Inside the try catch block or outside it?. For example, is option A or option B the correct approach or are they subjective choices? **Option A** CREATE PROCEDURE DummyProc BEGIN TRY BEGIN TRANSACTION INSERT sometabl...
In a SQL Server code block, what is the best place to place the commit transaction? Inside the try catch block or outside it?.
For example, is option A or option B the correct approach or are they subjective choices?
**Option A**
CREATE PROCEDURE DummyProc
BEGIN TRY
BEGIN TRANSACTION
INSERT sometable(a, b) VALUES (@a, @b)
INSERT sometable(a, b) VALUES (@b, @a)
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@trancount > 0 ROLLBACK TRANSACTION
DECLARE @msg nvarchar(2048) = error_message()
RAISERROR (@msg, 16, 1)
RETURN 55555
END CATCH
**Option B**
CREATE PROCEDURE DummyProc
BEGIN TRY
BEGIN TRANSACTION
INSERT sometable(a, b) VALUES (@a, @b)
INSERT sometable(a, b) VALUES (@b, @a)
END TRY
BEGIN CATCH
IF @@trancount > 0 ROLLBACK TRANSACTION
DECLARE @msg nvarchar(2048) = error_message()
RAISERROR (@msg, 16, 1)
RETURN 55555
END CATCH
IF @@trancount > 0 COMMIT TRANSACTION
In Option B, is there a possibility of some error happening when its doing a commit outside the
TRY-CATCH
block ?
user20358
(213 rep)
Mar 25, 2019, 10:15 PM
• Last activity: Mar 26, 2019, 12:15 PM
0
votes
3
answers
259
views
What is back-end programming?
I like to know what exactly is the back-end programming? Does it include offline databases? Everyone who designs and creates databases and tables is a back-end programmer? What do they mean exactly by server side programming? By which languages they do this and may someone gives some examples about...
I like to know what exactly is the back-end programming? Does it include offline databases? Everyone who designs and creates databases and tables is a back-end programmer? What do they mean exactly by server side programming? By which languages they do this and may someone gives some examples about some of those programs that are written for server and we call them back-end programs? Maybe its good to ask for which kind of projects/programs/applications we need back-end programming?
Sorry if this is duplicated, broad or boring, but I couldn't find my answers any other places!
user3486308
(151 rep)
May 27, 2018, 05:54 PM
• Last activity: May 27, 2018, 09:07 PM
0
votes
1
answers
5624
views
MYSQL - Operand should contain 1 column(s) - Nested Case statement
I have written the below query with nested case statements. The syntax checks out but when I run it I receive error code 1241: Operand should contain only 1 column(s). I have attempted to remove the parenthesis from the SELECT statements but it does not help and indicates there is a syntax error. Th...
I have written the below query with nested case statements. The syntax checks out but when I run it I receive error code 1241: Operand should contain only 1 column(s). I have attempted to remove the parenthesis from the SELECT statements but it does not help and indicates there is a syntax error.
This query is intended to select a data subset based on current time. The first case selects data from today's first shift. The second nested case determines if the current time the night portion of second shift (Between now and midnight 2nd shift) or the early morning portion of second shift between midnight and 4:30. If it is after midnight then date from today and today-1 is selected. Any ideas?
SELECT CASE WHEN current_time() BETWEEN CAST('6:00:00' AS TIME) AND CAST('16:30:00' AS TIME)
THEN
(SELECT infeedweight, outfeedweight, yield, time_stamp, num_checks_passed, num_checks_failed,TIME(time_stamp)
FROM workers_totals
WHERE time_stamp >= curdate())
ELSE
CASE WHEN (current_time() BETWEEN CAST('16:30:00' AS TIME) AND CAST('23:59:59' AS TIME))
THEN
(SELECT infeedweight, outfeedweight, yield, time_stamp, num_checks_passed, num_checks_failed,TIME(time_stamp)
FROM workers_totals
WHERE time_stamp >= CAST(CONCAT(curdate(),' 16:30:00') AS DATETIME) and CAST(CONCAT(curdate(),' 23:59:59') AS DATETIME))
ELSE
(SELECT infeedweight, outfeedweight, yield, time_stamp, num_checks_passed, num_checks_failed,TIME(time_stamp)
FROM workers_totals
WHERE (time_stamp >= CAST(CONCAT(curdate(),' 00:00:00') AS DATETIME) and CAST(CONCAT(curdate(),' 04:59:59') AS DATETIME))
OR (time_stamp >= CAST(CONCAT(curdate()-1,' 16:30:00') AS DATETIME) and CAST(CONCAT(curdate()-1,' 23:59:59') AS DATETIME)))
END
END
MilfordTechnologyGuy
(3 rep)
Feb 27, 2018, 10:55 PM
• Last activity: Feb 28, 2018, 02:24 AM
0
votes
1
answers
79
views
Access Send Email. Loop Not Building Table
I’m stumped on this one. I have an action item list on a fairly large Project Management DB. This list is datasheet that is embedded as a subform on a PopUp form from the Main Menu. On the Action Item table I have a [email] field that is used as a checkbox on the form. The user can then create an ac...
I’m stumped on this one. I have an action item list on a fairly large Project Management DB. This list is datasheet that is embedded as a subform on a PopUp form from the Main Menu. On the Action Item table I have a [email] field that is used as a checkbox on the form. The user can then create an action item check the box and I have a cmd button for “Send Selected Records”. (The code for this button is below). An email is created with the action item(s) embedded into an email as an HTML table with the assigned to person in the To line. I hope this makes sense. The email pulls from qrySendActionItems looking for the tasks with -1.
It works great… for some records. When building the HTML table of the selected it loops through qrySendActionItems. However it is NOT accurate. For example, I can select ten records it will only embed the first two. I can select another 10 and it will embed the first 8. Other times it works fine. It seems completely random of which records will be embedded and which will no work. Weird part, I can select a records that were missed and they will embed if they are the only by themselves. Something is breaking the Loop and as I said, it has me stumped. I believe the problem is around the 'Create each body row’ area.
I have verified the query is working and pulls selected records.
The qry is cleared as designed each time.
The emails address of ALL selected records populate correctly.
Everything works except the Loop to create the HTML table.
The really frustrating part… I know this code works because the exact same procedure sends out other lists just fine. It’s only the Action Items. I appreciate the help, Stack Overflow is awesome.
--adam
Private Sub cmdEmailAI_Click()
If Me.Dirty Then
DoCmd.Save
End If
Dim olApp As Object
Dim olTask As Object
Dim olItem As Variant
Dim db As DAO.Database
Dim rec As DAO.Recordset
Dim strQry As String
Dim aHead(1 To 10) As String
Dim aRow(1 To 10) As String
Dim aBody() As String
Dim lCnt As Long
'Create the header row
aHead(1) = "ID"
aHead(2) = "Project Name"
aHead(3) = "Status"
aHead(4) = "Start Date"
aHead(5) = "Due Date"
aHead(6) = "Finish Date"
aHead(7) = "ECD"
aHead(8) = "Assigned To"
aHead(9) = "Deliverable"
aHead(10) = "Comments"
lCnt = 1
ReDim aBody(1 To lCnt)
'Define
aBody(lCnt) = "" & Join(aHead, "") & ""
'Create each body row
strQry = "SELECT * From qrySendActionItems"
Set db = CurrentDb
Set rec = CurrentDb.OpenRecordset(strQry)
If Not (rec.BOF And rec.EOF) Then
Do While Not rec.EOF
lCnt = lCnt + 1
ReDim Preserve aBody(1 To lCnt)
aRow(1) = rec("ID")
aRow(2) = rec("ProjectName")
aRow(3) = rec("Status")
aRow(4) = Nz(rec("StartDate"), "")
aRow(5) = Nz(rec("DueDate"), "")
aRow(6) = Nz(rec("FinishDate"), "")
aRow(7) = Nz(rec("ECD"), "")
aRow(8) = Nz(rec("AssignedTo"), "")
aRow(9) = Nz(rec("Deliverable"), "")
aRow(10) = Nz(rec("Comment"), "")
aBody(lCnt) = "" & Join(aRow, "") & ""
rec.MoveNext
Loop
End If
aBody(lCnt) = aBody(lCnt) & ""
'create the email
Set olApp = CreateObject("Outlook.application")
Set olItem = olApp.CreateItem(0)
Set MyDB = CurrentDb
Set rst = MyDB.OpenRecordset("qrySendActionItems", dbOpenSnapshot, dbOpenForwardOnly)
Set oLook = CreateObject("Outlook.Application")
Set olns = oLook.GetNamespace("MAPI")
Set oMail = oLook.CreateItem(0)
'Build the Recipient List
With rst
Do While Not .EOF
strTO = strTO & ![EmailAddress] & ";"
.MoveNext
Loop
End With
olItem.Display
olItem.To = strTO
olItem.Subject = Date & ": Action Items| " & Me.txtTitle
olItem.HTMLBody = Join(aBody, vbNewLine)
olItem.Display
'Clears selected records
DoCmd.Hourglass True
DoCmd.SetWarnings False
DoCmd.OpenQuery "qrySendActionItemsClear", acViewNormal, acReadOnly
DoCmd.Hourglass False
DoCmd.SetWarnings True
Me.Refresh
End Sub

AdamB
(88 rep)
Feb 11, 2017, 10:27 PM
• Last activity: Feb 11, 2017, 11:58 PM
0
votes
1
answers
54
views
I am trying to run this code and I get an error at line 11
CREATE TABLE IF NOT EXISTS `tblproduct` ( `id` int(8) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `code` varchar(255) NOT NULL, `image` text NOT NULL, `price` double(10,2) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `product_code` (`code`) ) INSERT INTO `tblproduct` (`id`, `name`, `code`, `i...
CREATE TABLE IF NOT EXISTS
tblproduct
(
id
int(8) NOT NULL AUTO_INCREMENT,
name
varchar(255) NOT NULL,
code
varchar(255) NOT NULL,
image
text NOT NULL,
price
double(10,2) NOT NULL,
PRIMARY KEY (id
),
UNIQUE KEY product_code
(code
)
)
INSERT INTO tblproduct
(id
, name
, code
, image
, price
)
VALUES
(1, '3D Camera', '3DcAM01', 'product-images/camera.jpg', '1500.00'),
(2, 'External Hard Drive', 'USB02', 'product-images/external-hard-drive.jpg', '800.00'),
(3, 'Wrist Watch', 'wristWear03', 'product-images/watch.jpg', '300.00');
G1234
(1 rep)
Jul 27, 2016, 03:52 AM
• Last activity: Jul 27, 2016, 04:16 PM
1
votes
1
answers
710
views
Oracle PLSQL code recovery
I cannot connect to my database as admin, even using connect descriptor neither via RMAN. I am getting TNS-12514 error. I consider to install new instance. Questions: 1) Can I restore/recover PLSQL code from "dead" oracle database? 2) Where is the PLSQL stored? EDIT: My situation is described here:...
I cannot connect to my database as admin, even using connect descriptor neither via RMAN. I am getting TNS-12514 error.
I consider to install new instance.
Questions:
1) Can I restore/recover PLSQL code from "dead" oracle database?
2) Where is the PLSQL stored?
EDIT: My situation is described here: https://dba.stackexchange.com/questions/74208/ora-01033-oracle-initialization-or-shutdown-in-progress-caused-by-ora-10567-r
I consider to install new instance.
Questions:
1) Can I restore/recover PLSQL code from "dead" oracle database?
2) Where is the PLSQL stored?
EDIT: My situation is described here: https://dba.stackexchange.com/questions/74208/ora-01033-oracle-initialization-or-shutdown-in-progress-caused-by-ora-10567-r
Jakub P
(167 rep)
Oct 22, 2014, 09:31 AM
• Last activity: Oct 22, 2014, 01:59 PM
3
votes
1
answers
957
views
Improve select query performance
The following select query from my application is taking more than 200ms. The table has around 2 million rows. Is there any ways to improve the performance of this query ? select count(id) from table1 where status='A' and empID=123 Table Indexes PRIMARY KEY (`id`), KEY `empID` (`empID`), KEY `status...
The following select query from my application is taking more than 200ms. The table has around 2 million rows. Is there any ways to improve the performance of this query ?
select count(id) from table1 where status='A' and empID=123
Table Indexes
PRIMARY KEY (
id
),
KEY empID
(empID
),
KEY status
(status
),
KEY testID
(testID
),
CONSTRAINT fk_1
FOREIGN KEY (empID
) REFERENCES emp_info
(id
)
IS_EV
(181 rep)
May 27, 2014, 07:56 AM
• Last activity: Aug 4, 2014, 06:10 PM
Showing page 1 of 12 total questions